Jesús Amieiro

301 redirection between different domains with rewrite rules on Apache VirtualHost

In this example I explain how to make a 301 redirection (permanent redirection) between different domains with rewrite rules on Apache VirtualHost maintaining the full URI.

I want to redirect the HTTP and HTTPS queries made to the example.org domain to the example.com domain, in HTTPS mode.

I divide the code in 2 VirtualHosts: the first for the HTTP queries and the second for the HTTPS queries.

On each VirtualHost I redirect the HTTP/HTTPS queries using Apache Rewrite Rules.

Be careful that you will need an SSL certificate for the HTTPS queries on the example.org domain and, of course, another for the example.com domain.

<VirtualHost *:80>
        ServerName www.example.org
        ServerAlias example.org
        RewriteEngine On
        RewriteCond %{HTTPS} !=on
        RewriteRule ^/?(.*) https://www.example.com/$1 [R=301,L]
        ErrorLog ${APACHE_LOG_DIR}/example.com-error.log
</VirtualHost>

<VirtualHost *:443>
        ServerName www.example.org
        ServerAlias example.org
        SSLEngine on
        SSLCertificateFile /etc/letsencrypt/live/www.example.org/cert.pem
        SSLCertificateKeyFile /etc/letsencrypt/live/www.example.org/privkey.pem
        SSLCertificateChainFile /etc/letsencrypt/live/www.example.org/chain.pem
        RewriteEngine On
        RewriteRule ^/?(.*) https://www.example.com/$1 [R=301,L]
        ErrorLog ${APACHE_LOG_DIR}/example.com-error.log
</VirtualHost>
Exit mobile version