.htaccess rewrite GET variables w/ 301 redirect

2019-08-20 23:04发布

I'm trying to simultaneously do a 301 redirect and imporve my url structure by stripping the get variables.

I recently updated my website and Google has some old pages cached that have since moved. The structure looks like this

wwww.domain.com/locations.asp?zip=10001 <---OLD URL
wwww.domain.com/locations/?zip=10001 <---NEW URL

Right now I'm redirecting the old page to the new using the following line in my .htaccess file:

Redirect 301 /solar_panel_systems_zip.asp /zip-code/

The above works fine but I'd like the URL to be as follows:

wwww.domain.com/locations/zip/10001

I came across this post .htaccess rewrite GET variables and tried this rule but no luck :/

RewriteRule ^([\w\d~%.:_\-]+)$ index.php?page=$1 [NC]

I'm assuming this is because I'm 301 redirecting and doing a rewrite?

1条回答
冷血范
2楼-- · 2019-08-20 23:50

You want something like this in your htaccess file:

RewriteRule ^locations/zip/([0-9]+)$ /locations/?zip=$1 [L,QSA]

This will make it so when someone requests http://www.domain.com/locations/zip/10001, they will get served the contents of /locations.php?zip=10001.

To redirect the old URLs to the new ones, you will need to also add:

RewriteCond %{THE_REQUEST} ^(GET|HEAD)\ /locations(\.asp)?/?\?zip=([0-9]+)&?([^\ ]*)
RewriteRule ^ /locations/zip/%3?%4 [L,R=301]

So when someone tries to go to http://www.domain.com/locations.asp?zip=10001 or http://www.domain.com/locations/?zip=10001, they get redirected to http://www.domain.com/locations/zip/10001.

查看更多
登录 后发表回答