Fri. Aug 7th, 2020

How to create 301 redirect on Nginx & Apache

1 min read

Sometimes we need to do a 301 redirect on the Apache or Nginx server to direct the old page to the new page, or to move to the preferred domain name.

Apache 301 redirect (on Linux/Unix servers)

Redirect 301 domain without www to domain with www
Add the following code into .htaccess file:
RewriteEngine On
RewriteCond %{HTTP_HOST} !^www\.url\.com$ [NC]
RewriteRule ^(.*)$$1 [L,R=301]
Apache 301 redirect to a single url
RewriteEngine On
Redirect permanent /old-directory/old-file.html
Nginx 301 redirect
Add the following filter rules and rewrite rules to the corresponding Nginx configuration file:
server {
server_name ;
rewrite ^(.*)$1 permanent;

Not all the visits to station A are redirected to the specified page

server {
if ($host != ‘’ ) {
rewrite ^/(.*)$$1 permanent;