Rewriting old urls to pretty urls, and redirect ol

2019-06-07 05:26发布

问题:

I have some problems with .htaccess settings. My Website home page url is : http://www.domain.com/b/en/index.php ,and I use mod_rewrite to create pretty url : http://www.domain.com/en

This is my rewrite rules for pretty urls (It works):

RewriteRule ^en/(.*)$ /b/$1 [L,QSA,NC,PT]

That's pretty urls what I want, but when I redirect "old urls" to new urls, there are some problems.

My Chrome browser shows "www.domain.com redirected you too many times."

This is my old urls redirect to new rule:

RewriteRule ^b/en/(.*)$ /en/$1 [NC,L,R=301]

回答1:

This is a generic 2-part problem. You'll need to redirect the raw request to prettier one:

RewriteRule ^en/(.*)$ /b/en/$1 [L,QSA,NC]

RewriteCond %{THE_REQUEST} ^GET\ /b/(en)/(\S*) [NC]
RewriteRule ^b/ /%1/%2 [R=301,L]

Be sure to clear your browsers' cache before testing the new rules.



回答2:

I had a more generic use-case and I had to modify @hjpotter92's solution a bit.

Old URL structure: http://example.com/index.php?page=foo
New URL structure: http://example.com/foo

So I wanted to make the URLs "pretty" (i.e. SEO-friendly) but also have the old (ugly) URLs redirect to the new URLs so old bookmarks would still work.

Here's my solution:

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-l
RewriteRule ^/?(.*)$ /index.php?page=$1 [L,QSA,NC]

RewriteCond %{THE_REQUEST} ^GET\ \/?index\.php\?page=(\S*) [NC]
RewriteRule ^index.php /%1? [R=301,L]