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.

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
  • 13,690
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
  • 28,400
  • 21
  • 80
  • 117
Tero Kilkanen
  • 38,887