Nginx – redirecting with a regular expression

NGINX rewrite rules are quite simple and easy to understand. They change the part or complete URL in a client request (for example in case when you want to redirect your users from http to https, to another domain/subdomain, etc)

For example, the simple redirect with code 301 (moved permanently) from olddomain.com to newdomain.com can be achieved with:

server {
    listen 80;
    listen 443 ssl;
    server_name olddomain.com www.olddomain.com;
    return 301 $scheme://www.newdomain.com$request_uri;
}

In this case, $scheme and $request_uri are nginx variables and they are used to capture and replicate the values from the original request URL ($scheme is the protocol – ‘http’ or ‘https’ and $request_uri is the portion of the URL that follows the domain name – for example ‘/getUser?id=blabla’)

Examples

To add ‘www’ before the domain:

server {
    listen 80;
    listen 443 ssl;
    server_name domain.com;
    return 301 $scheme://www.domain.com$request_uri;
}

To remove the ‘www’:

server {
    listen 80;
    listen 443 ssl;
    server_name www.domain.com;
    return 301 $scheme://domain.com$request_uri;
}

To redirect all requests which doesn’t match already defined server and location blocks to specific home page
For example subdomain whose IP address points to the server but the server doesn’t have defined server or location block for this subdomain

server {
    listen 80 default_server;
    listen 443 ssl default_server;
    server_name _;
    return 301 $scheme://www.domain.com;
}

Also, you can add $request_uri variable above.

Forcing all Requests to Use SSL/TLS

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

Redirecting a subdomain with a regular expression to new subdomain

server {
    listen 80;
    server_name ~^((?<subdomain>.*)\.olddomain.com)$;
    return 301 $scheme://${subdomain}.newdomain.com$request_uri;
}

Redirecting subdomain to specific dir (with a regular expression)

server {
    listen 80;
    server_name ~^((?<subdomain>.*)\.)(?<domain>[^.]+)\.(?<tld>[^.]+)$;
    return 301 $scheme://${domain}.${tld}/${subdomain};
}

Source:
https://www.nginx.com/blog/creating-nginx-rewrite-rules/
https://stackoverflow.com/questions/9578628/redirecting-a-subdomain-with-a-regular-expression-in-nginx/31037713

Leave a Reply

Your email address will not be published. Required fields are marked *