A photo of Mitesh Shah

Mitesh Shah

Linux Expert | Automation Enthusiast | Security Consultant

Email Skype Github Twitter Resume Hire Me Keybase LinkedIn Stackoverflow


NGINX/Apache Redirect Rules

Overview

NGINX/Apache Redirect Rules

How to redirect example.in to example.com

NGINX

server {
  listen 80;
  server_name example.in;
  return 301 http://example.com$request_uri;
}

Apache

RewriteCond %{HTTP_HOST} ^example.in [NC]
RewriteRule ^(.*)$ http://example.com/$1 [L,R=301,NC]

How to redirect HTTP to HTTPS

NGINX

server {
  listen 80;
  server_name example.com;
  return 301 https://example.com$request_uri;
}

Apache

RewriteCond %{HTTPS}  off
RewriteCond %{HTTP:X-Forwarded-Proto} !https [NC]
RewriteCond %{HTTP_HOST} ^example.com [NC]
RewriteRule ^(.*)$ https://%{HTTP_HOST}/$1 [L,R=301,NC]

How to redirect HTTPS to HTTP

NGINX

server {
  listen 443;
  server_name example.com;
  return 301 http://example.com$request_uri;
}

Apache

RewriteCond %{HTTPS}  on
RewriteCond %{HTTP_HOST} ^example.com [NC]
RewriteRule ^(.*)$ http://%{HTTP_HOST}/$1 [L,R=301,NC]

Redirect non-www to www

NGINX

server {
  server_name example.com;
  return 301 $scheme://www.example.com$request_uri;
}

Apache

RewriteEngine on
RewriteCond %{HTTP_HOST} ^example.com [NC]
RewriteRule ^(.*)$ http://www.example.com/$1 [L,R=301,NC]

Redirect www to non-www

NGINX

server {
  server_name www.example.com;
  return 301 $scheme://example.com$request_uri;
}

Apache

RewriteEngine on
RewriteCond %{HTTP_HOST} ^www.example.com [NC]
RewriteRule ^(.*)$ http://example.com/$1 [L,R=301,NC]

NOTE!: You can directly test your .htaccess rules at http://htaccess.madewithlove.be/





Post Navigation