.htaccess使用参数重定向peaple友好URL

时间:2015-01-09 15:26:30

标签: php apache .htaccess mod-rewrite

我尝试使我的网站的网址更具可读性,但我无法做到这一点。

她是现在看起来像这样的网址的示例:

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=$1&uid=$2 [L,QSA]
RewriteRule ^([^/]+)/?$ /index.php?page=$1 [L,QSA]

它重写了像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错误。

我的问题是什么?

2 个答案:

答案 0 :(得分:0)

您需要另一个没有参数的重定向规则,您需要在内部转发规则中添加一些条件,以便/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=$1&uid=$2 [L,QSA]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^([^/]+)/?$ /index.php?page=$1 [L,QSA]

答案 1 :(得分:0)

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

# internal forward行:

上方插入此规则
# skip all files and directories from rewrite rules below
RewriteCond %{REQUEST_FILENAME} -d [OR]
RewriteCond %{REQUEST_FILENAME} -f
RewriteRule ^ - [L]