How To Force Apache to redirect from HTTP to HTTPS

Posted by Md. Mahidul Hasan on 12:14 AM with No comments
How To Force Apache to redirect from HTTP to HTTPS

Senario:
Suppose we have a website named "blog.mahidul.com". And I want if any user enter "blog.mahidul.com" to their browser it will automatically redirect to "https://blog.mahidul.com"


From RedHat:

First we will hash the followings from httpd.conf-

[mahidul@oracle ~]$ vim /etc/httpd/conf/httpd.conf
#NameVirtualHost *:80
#<VirtualHost *:80>
#    ServerAdmin root@localhost
#    DocumentRoot /var/www/html
#    ServerName localhost
#    ErrorLog logs/localhost-error_log
#    CustomLog logs/localhost-access_log common
#</VirtualHost>



Now we have to add/modify the virtual host file as below. It may be in the conf.d directory or it may also stay in your httpd.conf file (depends the way you have configured your server).

[mahidul@oracle ~]$ vim /etc/httpd/conf.d/mahidulsblog.conf
<VirtualHost *:80>
        RewriteEngine on
        ReWriteCond %{SERVER_PORT} !^443$
        RewriteRule ^/(.*) https://%{HTTP_HOST}/$1 [NC,R,L]
</VirtualHost>

<VirtualHost *:443>
    ServerAdmin aman@progoti.com
    DocumentRoot /var/www/html/mahidulsblog
    ServerName blog.mahidul.com
    ErrorLog logs/blog.mahidul.com-error_log
    CustomLog logs/blog.mahidul.com-access_log common

    <Directory /var/www/html/mahidulsblog>
        Options +ExecCGI
        AllowOverride Limit FileInfo Indexes
        DirectoryIndex index.cgi
        AddHandler cgi-script .cgi
    </Directory>

ErrorLog logs/ssl_error_log
TransferLog logs/ssl_access_log
LogLevel warn

SSLEngine on
SSLProtocol all -SSLv2
SSLCipherSuite ALL:!ADH:!EXPORT:!SSLv2:RC4+RSA:+HIGH:+MEDIUM:+LOW
SSLCertificateFile /etc/pki/tls/certs/localhost.crt
SSLCertificateKeyFile /etc/pki/tls/private/localhost.key

<Files ~ "\.(cgi|shtml|phtml|php3?)$">
    SSLOptions +StdEnvVars
</Files>

<Directory "/var/www/cgi-bin">
    SSLOptions +StdEnvVars
</Directory>


SetEnvIf User-Agent ".*MSIE.*" \
         nokeepalive ssl-unclean-shutdown \
         downgrade-1.0 force-response-1.0

CustomLog logs/ssl_request_log \
          "%t %h %{SSL_PROTOCOL}x %{SSL_CIPHER}x \"%r\" %b"

</VirtualHost>


Note: In debian/ubuntu like bistro the apache folder location will be at "/etc/apache2/sites-available/default" or "/etc/apache2/sites-available/[oursite]" configuration file.