带有 .htaccess 的个性化 URL

Vanity URLs with .htaccess

我需要实现个性化 urls,这是我的 .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= [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 是一个随机字符串,我想检查这个特定的 url

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=&readers=1 [L,QSA]

您需要在规则中使用锚点并将尾部斜杠设为可选:

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