Skip to Content

Redirect IP to Domain Name in Linux

How to redirect IP to FQDN with HTTPS in Apache Webserver using mod_rewrite (Ubuntu 18,20,22)?

The objective of the article is to rewrite the URL from http://192.168.1.1 to https://server.gateway.com/ezlogin using .htaccess


1. Enable the rewrite and alias module in Ubuntu.

root@ubuntu ~]# a2enmod rewrite alias

root@ubuntu ~]# systemctl restart apache2

2. Create a virtual host for the domain name with ports 80 and 443.

root@ubuntu ~]# vim /etc/apache2/sites-available/server.gateway.com.conf


<VirtualHost *:80>
 
ServerName server.gateway.com
DocumentRoot /var/www/html
 
<Directory /var/www/html>
AllowOverride All
</Directory>
 
</VirtualHost>

root@ubuntu ~]# vim /etc/apache2/sites-available/server.gateway.com-ssl.conf


<VirtualHost *:443>
 
ServerName server.gateway.com
DocumentRoot /var/www/html
 
<Directory /var/www/html>
AllowOverride All
</Directory>
 
</VirtualHost>
3. Edit the default apache configuration file and add "AllowOverride All"

root@ubuntu ~]# vim /etc/apache2/sites-available/000-default.conf


<VirtualHost *:80>
ServerAdmin webmaster@localhost
DocumentRoot /var/www/html
 
<Directory /var/www/html>
AllowOverride All
</Directory>
 
</VirtualHost>
4. Edit the default apache SSL configuration file and add "AllowOverride All"

root@ubuntu ~]# vim /etc/apache2/sites-available/default-ssl.conf


<IfModule mod_ssl.c>
<VirtualHost _default_:443>
ServerAdmin webmaster@localhost
DocumentRoot /var/www/html
 
<Directory /var/www/html>
AllowOverride All
</Directory>
 
SSLEngine on
SSLCertificateFile /etc/ssl/certs/apache-selfsigned.crt
SSLCertificateKeyFile /etc/ssl/private/apache-selfsigned.key
 
</VirtualHost>
</IfModule>
5. Create a .htaccess file and add the below rules. Replace below domain name with your domain name.

root@ubuntu ~]# vim /var/www/html/.htaccess


RewriteEngine On

RewriteCond %{HTTP_HOST} !^server.gateway.com$
RewriteRule ^(.*)$ https://server.gateway.com/$1 [R=301,L]

RedirectMatch ^/$ https://server.gateway.com/ezlogin/

 

Related Articles