Skip to content

Instantly share code, notes, and snippets.

@paulofreitas
Last active July 21, 2017 18:00
Show Gist options
  • Save paulofreitas/c37c1059847d7d05b427a9d4436bfde1 to your computer and use it in GitHub Desktop.
Save paulofreitas/c37c1059847d7d05b427a9d4436bfde1 to your computer and use it in GitHub Desktop.
Redirects Apache www URLs to non-www

Using mod_alias

HTTP only

<VirtualHost *:80>
    ServerName www.example.com
    Redirect permanent / http://example.com/
</VirtualHost>

<VirtualHost *:80>
    ServerName example.com
    # real server configuration
</VirtualHost>

HTTP/HTTPS

<VirtualHost *:80>
    ServerName www.example.com
    Redirect permanent / http://example.com/
</VirtualHost>

<VirtualHost *:80>
    ServerName example.com
    # real server configuration
</VirtualHost>

<VirtualHost *:443>
    ServerName www.example.com
    Redirect permanent / https://example.com/
</VirtualHost>

<VirtualHost *:443>
    ServerName example.com
    # real server configuration
</VirtualHost>

Force HTTPS

<VirtualHost *:80>
    ServerName example.com www.example.com
    Redirect permanent / https://example.com/
</VirtualHost>

<VirtualHost *:443>
    ServerName www.example.com
    Redirect permanent / https://example.com/
</VirtualHost>

<VirtualHost *:443>
    ServerName example.com
    # real server configuration
</VirtualHost>

Using mod_rewrite

HTTP/HTTPS

Apache 2.4+, detects HTTP/HTTPS automatically

RewriteEngine On
RewriteCond %{HTTP_HOST} ^www\.(.*)$ [NC]
RewriteRule ^ %{REQUEST_SCHEME}://%1%{REQUEST_URI} [R=301,L]

Apache 2.2+

RewriteEngine On

RewriteCond %{HTTPS} off
RewriteCond %{HTTP_HOST} ^www\.(.*)$ [NC]
RewriteRule ^ http://%1%{REQUEST_URI} [R=301,L]

RewriteCond %{HTTPS} on
RewriteCond %{HTTP_HOST} ^www\.(.*)$ [NC]
RewriteRule ^ https://%1%{REQUEST_URI} [R=301,L]

Force HTTPS

RewriteEngine On

RewriteCond %{HTTPS} off
RewriteCond %{HTTP_HOST} ^www\.(.*)$ [NC]
RewriteRule ^ https://%1%{REQUEST_URI} [R=301,L]

RewriteCond %{HTTPS} off
RewriteRule ^ https://%1%{REQUEST_URI} [R=301,L]

RewriteCond %{HTTPS} on
RewriteCond %{HTTP_HOST} ^www\.(.*)$ [NC]
RewriteRule ^ https://%1%{REQUEST_URI} [R=301,L]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment