【问题标题】:how to remove query string from url using htaccess如何使用 htaccess 从 url 中删除查询字符串
【发布时间】:2022-02-10 23:42:36
【问题描述】:

一旦我的朋友帮助我解决了这个问题,我就编写了这样的代码。其中example.com/blog-detail?slug=slugvalue 转到blog-detail.php,此网址example.com/project?slug=test 转到project.php

RewriteEngine ON
##Checking condition and getting matches in variables to be used while redirect in next rule.
RewriteCond %{THE_REQUEST} \s([^?]*)\?slug=(\S+)\s [NC]
RewriteRule ^ %1/%2? [R=301,L]

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(?:[^/]*)/(.*)/?$  blog-detail.php?slug=$1 [QSA,L]

我认为它只适用于博客详细信息页面,现在我面临这个网址的问题 https://www.example.com/project?slug=test,它把我重定向到 404 页面,你能帮我看看吗?

【问题讨论】:

标签: apache .htaccess mod-rewrite url-rewriting friendly-url


【解决方案1】:

用你展示的样本,尝试;请尝试遵循 htaccess 规则文件。请确保在测试您的 URL 之前清除您的浏览器缓存。

我在这里添加了 2 个解决方案,因此请使用第一个规则集或使用第二个规则集,一次只能使用一个。

第一种解决方案:为每个 php 文件设置 2 条不同的规则,请尝试以下规则。

RewriteEngine ON
###Rules for blog-detail.php redirect and rewrite.
##Checking condition and getting matches in variables to be used while redirect in next rule.
RewriteCond %{ENV:REDIRECT_STATUS} ^$
RewriteCond %{THE_REQUEST} \s(blog-detail)\?slug=(\S+)\s [NC]
RewriteRule ^ /%1/%2? [R=301,L]

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(?:[^/]*)/(.*)/?$  blog-detail.php?slug=$1 [QSA,L]

###Rules for project.php redirect and rewrite.
##Checking condition and getting matches in variables to be used while redirect in next rule.
RewriteCond %{ENV:REDIRECT_STATUS} ^$
RewriteCond %{THE_REQUEST} \s(project)\?slug=(\S+)\s [NC]
RewriteRule ^ /%1/%2? [R=301,L]

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(?:[^/]*)/(.*)/?$  project.php?slug=$1 [QSA,L]


第二个解决方案:一个通用的解决方案,通过捕获组来同时处理两种 php 文件。

RewriteEngine ON
###Rules for blog-detail.php OR project.php redirect and rewrite.
##Checking condition and getting matches in variables to be used while redirect in next rule.
RewriteCond %{ENV:REDIRECT_STATUS} ^$
RewriteCond %{THE_REQUEST} \s([^?]*)\?slug=(\S+)\s [NC]
RewriteRule ^ /%1/%2? [R=301,L]

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^([^/]*)/(.*)/?$  /$1.php?slug=$2 [QSA,L]

注意 1:请保留您的 php 文件(project.phpblog-detail.php)应与您的 htaccess 规则文件一起保存。

注意 2: 对于 JS/CS 重写/重定向: 您可能需要使用 base 标签来修复您的 js 和其他相关资源。如果您使用相对路径链接 js 文件,那么该文件显然会得到 404,因为它正在寻找 URL 路径。例如,如果 URL 路径是 /file/ 而不是 file.html,那么您的相关资源将从 /file/ 加载,这不是目录而是重写的 html 文件。要解决此问题,请使您的链接成为绝对链接或使用基本标签。在您的网页标题中添加此<base href="/">,以便您的相关链接可以从正确的位置加载。

【讨论】:

  • 第一个解决方案仅适用于博客详细信息页面,不适用于项目,如果我使用第二个解决方案,那么两个 url 都会转到 404 页面
  • @KunalVerma,现在请检查我的第二个解决方案,我现在编辑它,有一个错字,让我知道它是怎么回事。确保两个 php 文件都与您的 htaccess 文件一起存在。
  • 现在页面工作正常,但重定向不适用
  • 两个网址都以 slug 打开
  • 我已经更新了第二个解决方案,请检查并批准它
猜你喜欢
  • 2021-08-18
  • 1970-01-01
  • 2017-06-01
  • 1970-01-01
  • 1970-01-01
  • 2012-12-13
  • 2016-10-25
  • 1970-01-01
相关资源
最近更新 更多