简体   繁体   中英

htaccess canonical url

I'm having a little trouble with mod_rewrite for canonical urls. This is my current htaccess:

RewriteEngine On
RewriteBase /reads

RewriteRule ^search/([^/]*)/?$ search.php?q=$1 [L]
RewriteRule ^([^/]*)/([^/]*)/?$ view.php?title=$1&chapter=$2 [L]

I'm trying to rewrite these url: website.com/reads/how-to-cook/9 into website.com/reads/view.php?title=how-to-cook&chapter=9

In my PHP functions, calling view.php?title=xyz will list all the chapters in that title, adding &chapter=xx will load the chapter corresponding to selected title.

The script works fine in these cases:

website.com/reads/how-to-cook/9
website.com/reads/economy-blah/5/
website.com/reads/good-recipes/

But this one gives 404 error (omitting the trailing slash after the title), please tell me how to fix the error, explanation where the error might coming from would be really appreciated:

website.com/reads/good-recipes

Second question (forgive me if being too greedy here). How do I turn:

website.com/reads/how-to-cook/9
website.com/reads/economy-blah/5/

into

website.com/reads/how-to-cook/chapter-9
website.com/reads/economy-blah/chapter-5/

using mod_rewrite. Thank you!

Add these 2 lines

RewriteRule ^([^/]*)/([0-9]+)/?$ http://website.com/reads/$1/chapter-$2 [L,R=301]
RewriteRule ^([^/]*)?$ view.php?title=$1 [NC,L]

the first line changes the url which answers you second question. Essentially, it redirect user to new url and works only when the second argument is numerical. The second line defines the new condition which is missing in your rules. the complete rewrite rule set then will look like this

RewriteEngine On
RewriteBase /reads

RewriteRule ^([^/]*)/([0-9]+)/?$ http://website.com/reads/$1/chapter-$2 [L,R=301]

RewriteRule ^search/([^/]*)/?$ search.php?q=$1 [L]
RewriteRule ^([^/]*)?$ view.php?title=$1 [NC,L]
RewriteRule ^([^/]*)/([^/]*)/?$ view.php?title=$1&chapter=$2 [L]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM