0

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.

Shawn Vader
  • 103
  • 1
  • 4

2 Answers2

1

I would try something like this :

RewriteEngine On
RewriteCond %{HTTP_HOST} ^52\.17\.12\.123$ [OR] 
RewriteCond %{HTTP_HOST} ^ec2-52\.17\.12\.123\.eu-west-1\.compute\.amazonaws\.com$ 
RewriteRule (.*) http://www.example.com/$1 [R=301,L]
krisFR
  • 12,830
  • 3
  • 31
  • 40
  • In these cases it is best to use "if host does nost match X, redirect" approach. – Tero Kilkanen Apr 26 '15 at 15:32
  • @Tero Kilkanen You are right...By the way i just wanted to translate the OP `if..or...` But for sure it was not the most improved approach ;) – krisFR Apr 26 '15 at 17:08
1

RewriteCond %{HTTP_HOST} !^52.17.12.123.com$ means that the RewriteRule is applied whenever the hostname is not 52.17.12.123.com.

However, your goal is to redirect whenever the host is not your own hostname. Therefore you need to use this configuration for rewrites instead:

RewriteEngine On
RewriteCond %{HTTP_HOST} !^www.example.com$
RewriteRule ^ http://www.example.com/ [R=301]

This should accomplish your goal, and prevents the rewrite look for www.example.com.

I also added =301 to the rewrite rule, so that Apache will send 301 Moved Permanently redirect instead of 302 status code to the browser, which is the recommended way for doing SEO redirects.

Jenny D
  • 27,358
  • 21
  • 74
  • 110
Tero Kilkanen
  • 34,499
  • 3
  • 38
  • 58