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

问题描述 投票:0回答:3

使用以下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=xyzexample.com/xyz/section

我在这里做错了吗?

php .htaccess url-rewriting
3个回答
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
投票

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

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

在编写RageD建议的代码之前

(对不起,应该把它贴出来作为评论,但我需要换行)


1
投票

我测试了它,它的工作原理。试试这个:

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

我所做的只是逃避URL中的/,因为/是一个正则表达式分隔符。

© www.soinside.com 2019 - 2024. All rights reserved.