.htaccess 重定向 peaple friendly url 带参数

.htaccess redirect peaple friendly url with parameters

我试图让我网站的 URL 更具可读性,但我很难做到这一点。

她是 URL 现在的样例:

http://example.com/
http://example.com/index.php
http://example.com/index.php?page=home
http://example.com/index.php?page=profile&uid=483ec3a0-7e0f-32e6-f357-ac9311204246

它们必须看起来像:

http://example.com/
http://example.com/home/
http://example.com/profile/483ec3a0-7e0f-32e6-f357-ac9311204246/

这是我的 .htaccess 文件的内容:

Options +FollowSymLinks -MultiViews
# Turn mod_rewrite on
RewriteEngine On
RewriteBase /

# external redirect from /view.php?id=1 to /view/id/1
RewriteCond %{THE_REQUEST} ^[A-Z]{3,}\s/+index\.php\?page=([^\s&]+)&uid=([^\s&]+) [NC]
RewriteRule ^ /%1/%2/? [L,R=301]

RewriteCond %{THE_REQUEST} ^[A-Z]{3,}\s/+index\.php\?page=([^\s&]+) [NC]
RewriteRule ^ /%1/? [L,R=301]

# internal forward from /view/id/1 to /view.php?id=1
RewriteRule ^([^/]+)/([^/]+)/?$ /index.php?page=&uid= [L,QSA]
RewriteRule ^([^/]+)/?$ /index.php?page= [L,QSA]

它重写了正确的 URL,例如 http://example.com/index.php?page=profile&uid=483ec3a0-7e0f-32e6-f357-ac9311204246 -> http://example.com/profile/483ec3a0-7e0f-32e6-f357-ac9311204246/,但我每次都会收到 404 错误。如果我尝试调用 http://example.com/http://example.com/home/,我会收到 500 错误。

我的问题是什么?

您需要另一个无参数的重定向规则,并且您需要向内部转发规则添加一些条件,以便 /index.php 不匹配:

Options +FollowSymLinks -MultiViews
# Turn mod_rewrite on
RewriteEngine On
RewriteBase /

# external redirect from /view.php?id=1 to /view/id/1
RewriteCond %{THE_REQUEST} ^[A-Z]{3,}\s/+index\.php\?page=([^\s&]+)&uid=([^\s&]+) [NC]
RewriteRule ^ /%1/%2/? [L,R=301]

RewriteCond %{THE_REQUEST} ^[A-Z]{3,}\s/+index\.php\?page=([^\s&]+) [NC]
RewriteRule ^ /%1/? [L,R=301]

RewriteCond %{THE_REQUEST} ^[A-Z]{3,}\s/+index\.php($|\ ) [NC]
RewriteRule ^ /? [L,R=301]

# internal forward from /view/id/1 to /view.php?id=1
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^([^/]+)/([^/]+)/?$ /index.php?page=&uid= [L,QSA]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^([^/]+)/?$ /index.php?page= [L,QSA]

您似乎遇到了导致 500 的无限循环问题。这是由于最后 2 个路由规则没有跳过文件和目录的原因。

# internal forward 行上方插入此规则:

# skip all files and directories from rewrite rules below
RewriteCond %{REQUEST_FILENAME} -d [OR]
RewriteCond %{REQUEST_FILENAME} -f
RewriteRule ^ - [L]