Create an Nginx redirect and rewrite rule

Nginx redirect and rewrite rule.
Photo: Lukas Rodriguez, Pexels.

What is Nginx?

Nginx is an open source web server. As web server for intranet based solutions or websites. Nginx can also be used as a mail proxy, reverse proxy, HTTP Cache server and load balancer. Nginx is focused on delivering high performance with low processor and memory usage. Nginx is a highly efficient and offers great flexible 'configuration' capabilities as a server. This is partly why Nginx is the most widely used web server in the world (1).

There are often several options for the same solution. After all: All roads lead to Rome. You can test the options and ultimately choose the one that suits you best. Preferably use a test server for this. Testing on a production system is not recommended. Visitors can visit the website at the same time. And of course you want to provide them with an optimal user experience.


Google has been describing HTTPS as a ranking signal for its search engine and underlying search results since 2014. In other words if your website does not support HTTPS. It can affect the search results and the ranking your web pages are found at. Since Google is by far the biggest search engine with a market share of 90%+ (Example The Netherlands) compared to number 2: Bing with a relatively negligible user percentage of about 3%. It is very important to redirect HTTP to HTTPS. So that the web server does not accidentally keep serving the website over HTTP. Redirecting HTTP to HTTPS is easy to achieve.

In the server {} block, place the following code:

return 301$request_uri;

WWW to non-WWW and vice versa

It is recommended to offer a website only on WWW or only on non-WWW. Not both. Should you have web pages that can be found on multiple URLs (WWW and non-WWW) - or even multiple websites. Then these can harm your search position. The search engine then no longer rates the content as unique, but as duplicated content. As it is offered identically on several websites. The solution is easy to apply by forcing Nginx to display only the WWW or non-WWW website and redirecting the others.

In the server {} block, place the following code:

return 301$request_uri; or return 301$request_uri;

Website upgrade from JPG and PNG to WebP

WebP is a relatively new image file format for images. It uses image compression and makes images smaller on average 39% than images stored with the widely used standard: JPG compression. Up to 64% smaller than animated GIF and 45% smaller than PNG. Since, as a webmaster, you want your website to be displayed to the end user as quickly as possible. You can choose to use the WebP. Nginx can help with this by redirecting the old images to the new optimized ones. 

In the location {} block, place the following code:

# Check accept header for WebP from the browser, check if .webp is on the server disk.
  if ($http_accept ~* "webp")    { set $webp_accept "true"; }
  if (-f $request_filename.webp) { set $webp_local  "true"; }

  # If the WebP variant is available, serve Vary Accept.
  if ($webp_local = "true") {
    add_header Vary Accept;

  # If the WebP format is supported by the client (browser), serve it.
  if ($webp_accept = "true") {
    rewrite (.*) $1.webp break;

In the server {} block, place the following code:

# Lookup for inbound requests with extra WebP flag if advertised in Accept.
    if ($http_accept ~* "webp") { set $webp T; }
    proxy_cache_key $scheme$proxy_host$request_uri$webp;

    # Proxy requests pass to the remote servers.
    proxy_pass http://backend;
    proxy_cache my-cache;

Redirecting an old domain to a new domain with Nginx

The company name has changed and this also affects your domain name. You would like to automatically redirect visitors who are still using the old name (for example, from a business card, brochure, etc.). To the new domain name. There are some practical options. With a simple configuration option, you could refer the old to the new:

In the server {} block, place the following code:

Where the server listens to the old domain.


And simply redirect it to the new domain name.

return 301 $scheme://$request_uri

This applies for the full url. For example: redirects to 

Temporary redirect with rewrite

You may want to temporarily redirect a domain name to another domain name. For example, in case of maintenance.

In the server {} block, place the following code:

Where the server listens to the old domain and redirect it temporarily to another.

rewrite ^/$ redirect;

Canonical Server name

More or less the same dilemma just like the www and non www subject. When using multiple domain names. Nginx may publish the same web pages under different domain names. This can affect your ranking on search engines, search lists.

In the server {} block, place the following code:


Where the multiple domains listens are redirected it to the one main domain.

return 301$request_uri;

Nginx as as a reverse proxy

You can also use Nginx as a proxy for Docker containers or Node.js applications.

A reverse proxy operates on behalf of a web service. It intercepts traffic and routes it to an application of your choice. Based on the application port.

location / {

Rewite rules on selected browsers only

Of course it is also possible to apply a rewrite rule only when a visitor uses a particular browser. For example browsers without manufacturer support like Internet Explorer. Which despite its age and unsupported status, is yet still widely used

if ($http_user_agent ~ MSIE) {
rewrite ^/$ redirect;

For example, you can redirect these visitors to an old browser friendly, version of the website.

Proxy passing an external script or file with Nginx 

Nginx has a simple solution, when you want to proxy a file or script from another server and domain. Where it appears to be offered from the main domain. (At least that's how the end user sees it). Served from the domain of the main base website, where of course this main website is on another server. But actually the script comes from another server and Nginx just masks or reroute it. Just the way you look at it.

location = /yourscript.js {
                proxy_set_header Host;
                proxy_buffering on;
    proxy_ssl_server_name on;
    proxy_ssl_session_reuse off;

Source reference