Apache httpd.conf for redirecting ip to hostname

Viewed 78047

I have external IP and hostname configured for my machine.

Inside the application, I am using only the domain names to access the APIs. So when i try to access my APIs through IP address, it shows 302 Moved temporarily error. So, for request(for Homepage) that hits the server with IP address, It should redirect to hostname.

That is, when user hits https://XX.XX.XX.XX/main it should be redirected to https://ayz-abc.mysite.com/main

For this I tried using the redirect in httpd.conf of apache.

<VirtualHost XX.XX.XX.XX>

DocumentRoot "/var/www/html"
#ServerName ayz-abc.mysite.com/

 # Other directives here
 RewriteEngine On
 RewriteRule /.* https://ayz-abc.mysite.com/ [R]

</VirtualHost>

I have also tried with the following

<VirtualHost *.portnum>
DocumentRoot "/var/www/html"
RewriteEngine On
RewriteCond %{HTTPS} on
RewriteRule  https://XX.XX.XX.XX/main https://ayz-abc.mysite.com/main [R=301,L]
</VirtualHost>

Plsssss help me.

6 Answers

This will redirect all request to IP to the similar on your domain

<IfModule mod_rewrite.c>

RewriteEngine on

RewriteCond %{HTTP_HOST} ^12\.34\.56\.78$

RewriteRule ^/(.*)$  https://ayz-abc.mysite.com/$1 [L,R=301]

</IfModule>

If you are using https domain than add following:

# BEGIN HTTPS Redirection Plugin
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteCond %{SERVER_PORT} !^443$
RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]

RewriteCond %{HTTP_HOST} ^XX\.XX\.XX\.XX$
RewriteRule ^(.*)$ https://your-domain-name.com/$1 [L,R=301]
</IfModule>
# END HTTPS Redirection Plugin

We are using https redirection plugin on site. Above block of code is generated by the plugin and we added only two lines in the code block. Below two lines are responsible to set IP to Domain redirection:

RewriteCond %{HTTP_HOST} ^XX\.XX\.XX\.XX$
RewriteRule ^(.*)$ https://your-domain-name.com/$1 [L,R=301]

Here ^XX.XX.XX.XX$ is your IP address, replace it like this: ^12.34.56.78$ with your server IP.

Thanks

Related