How to Redirect a URL in NGINX

Channel: Linux
Abstract: 1. Redirect All Request to Specific URL This will redirect all incoming requests on domain to url http//anotherdomain.com/) with corresponding request

This tutorial will help you to how to redirect requests to another domain in NGINX web servers. It is required if you have planned or changed your domain name and want to redirect traffic to new domain from old domain server.

First of all edit your domain configuration file in NGINX in your favorite editor and add the configuration as per your requirements of redirection.

$ vi /etc/nginx/sites-enabled/mydomain.com.conf
1. Redirect All Request to Specific URL

This will redirect all incoming requests on domain to url http://anotherdomain.com/dir1/index.php, as configured below.

server {
    listen 192.168.1.100:80;
    server_name mydomain.com;
    return 301 http://anotherdomain.com/dir1/index.php;
}
2. Redirect All Request to Other Domain

This will redirect all incoming requests on domain to another domain (http://anotherdomain.com/) with corresponding request url and query strings.

server {
    listen 192.168.1.100:80;
    server_name mydomain.com;
    return 301 http://anotherdomain.com$request_uri;
}
3. Redirect Requests with Protocol Specific

This will redirect all incoming requests on domain to another domain (http://anotherdomain.com/) with corresponding request url and query strings. Also it will use same protocol on redirected url.

server {
    listen 192.168.1.100:80;
    server_name mydomain.com;
    return 301 $scheme://anotherdomain.com$request_uri;
}

After making above changes, restart your NGINX server to reload newly added configuration.

Ref From: tecadmin
Channels: nginx

Related articles