What is wrong with this .htaccess code?

2019-09-21 15:10发布

问题:

I need to change article and profile links in my site to dynamic ones. i.e.

  • for article: site.com/article.php?id=12 becomes site.com/article/this_is_title_of_article
  • for profile: site.com/ref.php?user=23 becomes site.com/john_doe

So I wrote this to .htaccess:

RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-l
RewriteRule ^(.*)$ ref.php?user=$1 [QSA,L]
RewriteRule ^articles/(.*)$ article.php?user=$1 [QSA,L]

So, for the profile it works. You can type site.com/username, and it works. But, for the articles it does not- it just does not display anything.

I can't understand why if username is more than one word, it does not add underscores between the words: even if I add to the URL like site.com/john_doe it won't work.

So, pretty much, the above code works only for username AND if that username is only one word.

回答1:

The rules are evaluated from top to bottom, so most likely your user rule is catching everything before your articles rule gets a chance.

Try this:

RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-l
RewriteRule ^articles/(.*)$ article.php?user=$1 [QSA,L]
RewriteRule ^(.*)$ ref.php?user=$1 [QSA,L]