将example.com/section.php?username=xyz重写为example.com/xyz/section

时间:2010-12-20 17:21:18

标签: php .htaccess url-rewriting

使用以下htaccess,我能够将example.com/profile.php?username=xyz重写为example.com/xyz

RewriteEngine On
RewriteRule ^([a-zA-Z0-9_-]+)$ profile.php?user=$1
RewriteRule ^([a-zA-Z0-9_-]+)/$ profile.php?user=$1

在上面添加以下内容,

RewriteRule ^([a-zA-Z0-9_-]+)/section$ section.php?user=$1
RewriteRule ^([a-zA-Z0-9_-]+)/section/$ section.php?user=$1

未将example.com/section.php?username=xyz解析为example.com/xyz/section

我在这里做错了吗?

3 个答案:

答案 0 :(得分:1)

首先:说话方式恰恰相反:您展示的规则是将/xyz内部的请求重写为/profile.php?username=xyz而将重写为反之亦然。

现在,如果您想要将/xyz/section内部的请求内部重写为/section.php?username=xyz,其中sectionxyz是可变的,请尝试以下规则:

RewriteRule ^([a-zA-Z0-9_-]+)/?$ profile.php?user=$1
RewriteRule ^([a-zA-Z0-9_-]+)/([^/]+)/?$ $2.php?user=$1

答案 1 :(得分:1)

我测试了它并且它有效。试试这个:

RewriteRule ^([a-zA-Z0-9_-]+)\/section$ section.php?user=$1
RewriteRule ^([a-zA-Z0-9_-]+)\/section\/$ section.php?user=$1

由于/是正则表达式分隔符,我所做的就是转义网址中的/

答案 2 :(得分:1)

要在正确的目录中查找静态文件(images,css)而不必编写文件地址,请执行以下操作:

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d

在编写RageD建议的代码之前

(抱歉,应该将其发布为评论,但我需要换行)

相关问题