带有.htaccess的虚荣网址

时间:2017-09-18 17:44:04

标签: .htaccess vanity-url

我需要实现虚荣网址,这是我的.htaccess文件

# check if mod_rewrite is present
<IfModule mod_rewrite.c>

  #turns it on
  RewriteEngine on

  #if the requested url isn't a file or a dir
  RewriteCond %{REQUEST_FILENAME} !-f
  RewriteCond %{REQUEST_FILENAME} !-d

  #if the request does not end with .gif, .png or .jpg
  RewriteCond %{REQUEST_URI} !(\.gif|\.jpg|\.png)$ [NC]

  #process book.php, no matter what was in the url
  RewriteRule ^(.*)$ /book.php?book_id=$1 [L,QSA]

</IfModule>

此翻译正常。

www.mydomain.com/foo -> www.mydomain.com/book.php?book_id=foo

现在我需要一个更具体的条件:

www.mydomain.com/foo/readers -> www.mydomain.com/book.php?book_id=foo&readers=1

虽然readers没有变化,但foo是随机字符串,我想查看此特定网址

www.mydomain.com/foo/readers -> valid
www.mydomain.com/foo/readers?q=hello -> valid
www.mydomain.com/foo/reader -> invalid
www.mydomain.com/foo/readers/bar -> invalid
www.mydomain.com/foo/bar/readers -> invalid

#I tried many solutions like this but i can't get the desired result
RewriteRule ^(.*)[/]readers /book.php?book_id=$1&readers=1 [L,QSA]

1 个答案:

答案 0 :(得分:2)

您需要在规则中使用锚点并使尾随斜杠可选:

RewriteRule ^([^/]+)/readers/?$ /book.php?book_id=$1&readers=1 [L,QSA,NC]