What is wrong with this URL rewrite?
I want (for example)
discuss/1/title/where-are-you
to output
discussPage.php?开发者_运维百科id=1&title=where-are-you
I have the following commands in a .htaccess
file which is in the same directory as discussPage.php
:
# Enable Rewriting
RewriteEngine on
# Rewrite user URLs
# Input: discuss/ID/title/TITLE
# Output: discussPage.php?tid=NAME&title=TITLE
RewriteRule ^discuss/(\w+)/(\w+)/(\w+)/?$ discussPage.php?id=$1&title=$3
Right now I am getting a 404
error when I try to visit a page like discuss/1/title/where-are-you
even though discussPage.php?id=1&title=where-are-you works fine.
P.S. mod_rewrite
is enabled (i have used it for other purposes).
Your problem is that \w does not match the "-" in the last bit.
You can simply allow dashes in there using a broader character class like [\w-]+
. I would be careful with solutions like [^/]
because they allow anything except a slash, which is quite permissive. White-lists are always safer and avoid surprises.
# Enable Rewriting
RewriteEngine on
# Rewrite user URLs
# Input: discuss/ID/title/TITLE
# Output: discussPage.php?tid=NAME&title=TITLE
RewriteRule ^discuss/(\w+)/(\w+)/([\w-]+)/?$ discussPage.php?id=$1&title=$3
Note that the -
has to be last in the character class, otherwise you should escape it, because if it's in between two other characters it behaves as a range, like in [a-z]
.
To debug, you can always echo $_SERVER['QUERY_STRING'];
But I believe the correct code would be something like this.
RewriteEngine on
RewriteBase /
RewriteRule ^discuss/([0-9]+)/title/([a-z0-9\-]+)?$ discussPage.php?id=$1&title=$2 [NC,QSA]
You might want to fix your RewriteBase value, though.
Also - as seen in the last condition, you can only have alphanumeric characters and hyphens in the where-are-you
part. (but something tells me you won't be needing other characters!)
Works for me:
RewriteEngine On
RewriteBase /
RewriteRule ^discuss/([^/]+)/([^/]+)/([^/]+)/?$ discussPage.php?id=$1&title=$3 [R]
精彩评论