How can I make a stack-overflow style user URL?
I'd like to map:
mywebsite.com/users/
-> mywebsite.com/users/users.php
mywebsite.com/users
-> mywebsite.com/users/users.php
mywebsite.com/users/username
-> mywebsite.com/users/user.php?name=username
At present, I'm 开发者_C百科using this .htaccess in the users directory:
RewriteEngine On
RewriteRule ^([a-zA-Z0-9_])*$ user.php?name=$1 [L]
RewriteRule ^.*$ users.php [L]
However, it never generates the user.php?name=$1
URL.
Why doesn't it work?
Here are the rules (place in .htaccess in website root folder. If placed elsewhere some tweaking is required):
Options +FollowSymLinks -MultiViews
RewriteEngine On
RewriteBase /
# 1
RewriteRule ^users/?$ /users/users.php [L]
# 2
RewriteCond %{REQUEST_URI} !^/users/users?\.php
RewriteRule ^users/([^/]+)$ /users/user.php?name=$1 [QSA,L]
Rule #1 will match fist 2 URLs of yours.
Rule #2 will work with specific user mapping. It will ensure that it does not rewrite already rewritten URLs.
UPDATE:
If you want to place it into .htaccess file in /users/
folder, then this URL mywebsite.com/users
(without trailing slash) most likely will not work.
But in any case -- here are the rules:
Options +FollowSymLinks -MultiViews
RewriteEngine On
# 1
RewriteRule ^$ users.php [L]
# 2
RewriteCond %{REQUEST_URI} !^/users/users?\.php
RewriteRule ^([^/]+)$ user.php?name=$1 [QSA,L]
It looks to me like it is applying both rules in sequence: the url matches the first rule, so it adds user.php?name=$1
, and then it matches the second rule, so it replaces the string with users.php
. If that is the problem, then for your particular case you could fix it by replacing the second regular expression with ^/?$
.
精彩评论