Vanity URLs with .htaccess

625 views Asked by At

I need to implement vanity urls and this is my .htaccess file

# 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>

This translation works correctly.

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

Now i need a more specific condition:

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

While readers doesn't change, foo is a random string and i'd like to check this specific 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=$1&readers=1 [L,QSA]
1

There are 1 answers

5
anubhava On BEST ANSWER

You need to use anchor in your rule and make trailing slash optional:

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