What is wrong with this .htaccess code?

2019-09-21 15:11发布

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条回答
孤傲高冷的网名
2楼-- · 2019-09-21 15:40

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]
查看更多
登录 后发表回答