Shawn Vader
Shawn Vader

Reputation: 12385

Apache server config redirect from IP to domain name EC2

I am running an apache webserver on a linux EC2 instance.

The problem is that you can access the server using the IP address, DNS and the domain name. This causes a problem for SEO and I want to tidy it up.

I have read on the apache documentation that you can do a mod_rewrite and this needs to be done in the httpd.conf if you have root access otherwise in the .htaccess for per directory override. I have root access so I am trying to change the httpd.conf

If the user types in http://52.17.12.123/ or http://ec2-52.17.12.123.eu-west-1.compute.amazonaws.com/

I want them to be redirected to www.example.com

This is what I tried

<VirtualHost *:80>
 DocumentRoot "/var/www/html/my-website"
 # Other directives here
 RewriteEngine On
 RewriteCond %{HTTP_HOST} !^52.17.12.123.com$
 RewriteRule /* http://www.example.com/ [R]
</VirtualHost>

It seems to partially work but www.example.com does not load due to to many redirects.

--EDIT-- Thanks, so now in my httpd.conf I now have the following configuration

Listen 80

NameVirtualHost *:80

DocumentRoot "/var/www/html/my-website"

RewriteEngine On
RewriteCond %{HTTP_HOST} !^(www\.example\.com)$ [NC]
RewriteRule ^/(.*)$ http://www.example.com [R=301,L]

It is all working correctly now

Upvotes: 1

Views: 1057

Answers (1)

Justin Iurman
Justin Iurman

Reputation: 19016

It seems to partially work.
I doubt, considering the rule you currently have in your httpd.conf.

You can have it this way

RewriteEngine On
RewriteCond %{HTTP_HOST} !^www\.example\.com$ [NC]
RewriteRule ^/(.*)$ http://www.example.com/$1 [R=301,L]

Upvotes: 1

Related Questions