0
votes

I'm using .htaccess to take URLs that look like:

/index.php?page=2

and rewrite them to, for example:

/contact-us

I want to do two things:

When loading /contact-us, show page /index.php?page=2 but keep the friendly URL. I know this looks something like:

RewriteRule ^contact-us$ "index\.php\?page\=2" [L]

Which does work ok. But now I also want people who navigate to /index.php?page=2 to end up on /contact-us - how do I achieve this as a 301 redirect in combination with the friendly URL rewrite?

2

2 Answers

0
votes

Not sure why you are using quotes and escapes in target portion of your rewrite rule. The target portion is not a regular expression. That can simply look like:

RewriteRule ^contact-us$ /index.php?page=2 [L]

To redirect the index.php?page=2 you will need to do the following. This rule MUST be before the rule above or you will get in rewrite loop.

RewriteCond %{REQUEST_URI}  ^/index\.php$
RewriteCond %{QUERY_STRING} ^page=2$
RewriteRule .* /contact-us [R=301,L]

Here you are setting two rewrite conditions: that the page is /index.php and that the query string is page=2 (and only page=2). The R=301 flag will force an external rewrite to /contact-us and also send and HTTP 301 header.

0
votes

You can use this code in your DOCUMENT_ROOT/.htaccess file:

RewriteEngine On
RewriteBase /

RewriteCond %{THE_REQUEST} /index\.php\?page=2[&\s] [NC]
RewriteRule ^ contact-us? [R=302,L,NE]

RewriteRule ^contact-us/?$ index.php?page=2 [L,QSA,NC]