Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Permanent redirect via apache rewrite rules

I am trying to write a rule to permenantly redirect a domainname to another domain name

RewriteCond %{HTTP_HOST} ^www.companyname1.com$
RewriteRule ^(.*)$ http://www.companyname2.com/$1 [R=301,L]

This only works if the user remembers to type in www, if the user does not type in www in the url, the page will load but the image links will be broken.

Does anyone know how to adjust the above rule to it works with and without www?

I am using a LAMP configuration, apache 2 on redhat.

like image 302
oshirowanen Avatar asked Apr 05 '11 14:04

oshirowanen


People also ask

How do I create a temporary and permanent redirect in Apache?

As with the Redirect directive, you can specify the type of redirect by adding the redirect code before the URL location rules. In order for your changes to take effect, you'll need to restart Apache. On a modern Ubuntu server, you can do this using systemctl : sudo systemctl restart apache2.

What is rewrite rule in Apache?

RewriteRule specifies the directive. pattern is a regular expression that matches the desired string from the URL, which is what the viewer types in the browser. substitution is the path to the actual URL, i.e. the path of the file Apache servers. flags are optional parameters that can modify how the rule works.

What is the difference between redirect and rewrite?

Simply put, a redirect is a client-side request to have the web browser go to another URL. This means that the URL that you see in the browser will update to the new URL. A rewrite is a server-side rewrite of the URL before it's fully processed by IIS.


2 Answers

You can supply several optional Rewrite-Conditions with [OR]:

RewriteCond %{HTTP_HOST} ^www.companyname1.com$ [OR]
RewriteCond %{HTTP_HOST} ^companyname1.com$
RewriteRule ^(.*)$ http://www.companyname2.com/$1 [R=301,L]

This should do the trick. The first Rewrite-Condition fires, if www is present, the second one fires, if www has been forgotten.

like image 138
Demento Avatar answered Oct 20 '22 00:10

Demento


The redirect was not working for me and I had to adjust it, below is a working version based on the answer by @Demento.

# Parmenent redirect to webdesign.danols.com of all pages
RewriteEngine on
RewriteCond %{HTTP_HOST} ^www.kingston-web-design.com [OR]
RewriteCond %{HTTP_HOST} ^kingston-web-design.com
RewriteRule ^(.*)$ http://webdesign.danols.com.com$1 [R=301,L]
like image 38
Daniel Sokolowski Avatar answered Oct 19 '22 22:10

Daniel Sokolowski