重写网站 URL 以删除查询字符串变量问号?

时间:2021-03-29 08:10:33

标签: apache .htaccess mod-rewrite

我有一个包含查询字符串变量的当前 url。我想删除它们,以便只有查询字符串的第二部分可见。
来自:mysite.com/posts?post=45&tab=profile
致:mysite.com/posts/45/profile
当前 .htaccess 文件

RewriteEngine on
RewriteBase /

RewriteCond %{THE_REQUEST} \s/+access/(\S*) [NC]
RewriteRule ^ /%1 [R=301,L,NE]

RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{DOCUMENT_ROOT}/access/$1.php -f
RewriteRule ^(.+?)/?$ access/$1.php [L,NC]

网站地图

index.php
/access
    -dashboard.php
    -posts.php
    -account.php

这个查询字符串总是有参数 1,但可能有也可能没有参数 2,这取决于他们在屏幕上点击了什么。

1 个答案:

答案 0 :(得分:1)

像这样:

Options -MultiViews
RewriteEngine on
RewriteBase /

RewriteCond %{THE_REQUEST} \s/+access/(\S*) [NC]
RewriteRule ^ /%1 [R=301,L,NE]

RewriteCond %{REQUEST_FILENAME} -f [OR]
RewriteCond %{REQUEST_FILENAME} -d
RewriteRule ^ - [L]

# 2 parameter rule
RewriteCond %{DOCUMENT_ROOT}/access/$1.php -f
RewriteRule ^([\w-]+)/([\w-]+)/([\w-]+)/?$ access/$1.php?post=$2&tab=$3 [QSA,L]

# 1 parameter rule
RewriteCond %{DOCUMENT_ROOT}/access/$1.php -f
RewriteRule ^([\w-]+)/([\w-]+)/?$ access/$1.php?post=$2 [QSA,L]

# php extension
RewriteCond %{DOCUMENT_ROOT}/access/$1.php -f
RewriteRule ^(.+?)/?$ access/$1.php [L,NC]

# php extension
RewriteCond %{DOCUMENT_ROOT}/$1.php -f
RewriteRule ^(.+?)/?$ $1.php [L,NC]
  • 选项 MultiViews(请参阅 http://httpd.apache.org/docs/2.4/content-negotiation.html)由运行 before Apache's content negotiation modulemod_rewrite 使用,并使 Apache 服务器匹配文件的扩展名。因此,如果 /file 是 URL,则 Apache 将提供 /file.html
相关问题