How to do a redirect via .htaccess?

4

I'd like to redirect 15 to 20% static% from one site to another url, type:

urls to http://meusite.com.br/home1.html
http://novosite.com.br to http://meusite.com.br/home2.html
http://novosite.com.br to http://meusite.com.br/home3.html
http://novosite.com.br to http://meusite.com.br/home4.html
http://novosite.com.br to http://meusite.com.br/home5.html

How can I do this with .htaccess?

    
asked by anonymous 06.08.2015 / 02:00

1 answer

6

You should use the [R=301] or [R=302] flag just to indicate the type of targeting.

In case if 301 is a permanent redirect, then 302 is temporary redirect.

In the meusite.com.br site you should create a .htaccess root folder with the following content:

RewriteRule ^home1\.html$ http://novosite.com.br [R=301]
RewriteRule ^home2\.html$ http://novosite.com.br [R=301]
RewriteRule ^home3\.html$ http://novosite.com.br [R=301]
RewriteRule ^home4\.html$ http://novosite.com.br [R=301]
RewriteRule ^home5\.html$ http://novosite.com.br [R=301]
RewriteRule ^home6\.html$ http://novosite.com.br [R=301]

If the url paths in the new site are the same as in the old one, you should do this:

RewriteRule ^home1\.html$ http://novosite.com.br/$0 [R=301]
RewriteRule ^home2\.html$ http://novosite.com.br/$0 [R=301]
RewriteRule ^home3\.html$ http://novosite.com.br/$0 [R=301]
RewriteRule ^home4\.html$ http://novosite.com.br/$0 [R=301]
RewriteRule ^home5\.html$ http://novosite.com.br/$0 [R=301]
RewriteRule ^home6\.html$ http://novosite.com.br/$0 [R=301]

$0 already identifies the url path because of regex

If all urls have this default home1.html à home20.html, you can simplify it to:

RewriteRule ^home(\d+)\.html$ http://novosite.com.br/$0 [R=301]

\d+ represents "any number", then it will recognize home1.html or home10001.html for example.

You can change [R=301] to [R=302] if the redirect is temporary and in the future it will be the old site again.

Note that you may also want to use the [QSA] flag if you want to target urls with querystring, for example if you access meusite.com.br/home1.html?foo=a it should redirect to novosite.com.br/home1.html with .htaccess

But if you use the [QSA] flag then the redirect will thus novosite.com.br/home1.html?foo=a

For this use this:

RewriteRule ^home(\d+)\.html$ http://novosite.com.br/$0 [QSA,R=301] 
    
06.08.2015 / 02:12