How to Create Rewrite Rules in Nginx

NGINX rewrite rules provide a powerful way to modify and manage URL requests on your web server. These rules are essential for redirecting URLs, changing URL structures, and improving SEO. By leveraging rewrite rules, you can ensure that users and search engines can access your content efficiently and maintain a clean and organized URL structure. Mastering rewrite rules allows you to enhance the functionality and flexibility of your web server, providing a better overall user experience.

This guide will explain how to create rewrite rules in NGINX, providing clear examples and steps to help you configure your server to handle URL modifications effectively.

NGINX Rewrite Rules: Return Directive

The NGINX return directive is a powerful tool for managing server responses. It’s primarily used to redirect clients to different URLs or to send specific status codes. This directive simplifies redirecting traffic, particularly when moving or restructuring your website. It’s essential for SEO and maintaining user experience during transitions. Let’s examine a unique example to understand its application:

Example: Suppose you want to redirect users from an old page to a new one. In your NGINX configuration file, you might use the return directive as follows:

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

In this example, any request to oldsite.com is permanently redirected to newsite.com, preserving the request URI. The 301 status code indicates a permanent redirect, informing search engines to update their indexing.

NGINX Rewrite Rules: Rewrite Directive

The NGINX rewrite directive is used to alter request URIs in various ways before further processing. It’s more versatile than the return directive, allowing complex URL manipulations based on conditions. This feature is crucial for creating SEO-friendly URLs and managing legacy links.

Example: Imagine you need to convert a dynamic URL to a static-looking one for better SEO. You could use the rewrite directive like this:

server {
    listen 80;
    server_name example.com;
    location /products {
        rewrite ^/products/([0-9]+)/([0-9]+)$ /product?id=$1&page=$2 last;
    }
}

In this scenario, a URL like example.com/products/123/2 is internally rewritten to example.com/product?id=123&page=2. The last flag indicates that the rewriting process should stop and the new URI should be re-evaluated.

Example NGINX Rewrite Rules

Implementing HTTPS Rewrite Rules in NGINX

Ensuring secure connections via HTTPS is crucial for data security. The NGINX rewrite directive can redirect all HTTP traffic to HTTPS, enhancing the security of data in transit.

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

In this example, HTTP requests to example.com are redirected to HTTPS, ensuring encrypted communication.

Streamlining URLs: Duplicate Slash Removal in NGINX Rewrite Rules

Occasionally, URLs might contain duplicate slashes, leading to confusion or errors. NGINX’s rewrite directive efficiently handles this by converting URLs with double slashes to a single slash.

server {
    server_name example.com;
    if ($request_uri ~* "\/\/") {
        rewrite ^/(.*)/$ /$1 permanent;
    }
}

This rule streamlines URLs by removing any redundant slashes.

Directory Redirection: NGINX Rewrite Rules in Action

When reorganizing or moving resources, redirecting entire directories efficiently is often necessary. NGINX facilitates this through its rewrite rule.

location ^~ /old-directory/ {
    rewrite ^/old-directory/(.*)$ /new-directory/$1 permanent;
}

This command redirects all requests from /old-directory/ to /new-directory/.

Query String Manipulation Using Rewrite Rules in NGINX

Altering URLs based on query strings can be particularly beneficial during site redesigns. NGINX rewrite rules allow for dynamic URL restructuring based on these parameters.

if ($args ~ "^id=(.*)&lang=(.*)") {
    set $id $1;
    set $lang $2;
    rewrite ^/page.php$ /page/$lang/$id? permanent;
}

Here, the rewrite rule transforms complex query strings into more streamlined URLs.

Ensuring Uniform URLs: Trailing Slash in NGINX Rewrite Rules

Uniformity in URL structure, such as trailing slash, can be critical for site consistency and SEO.

rewrite ^([^.]*[^/])$ $1/ permanent;

This rule ensures all URLs end with a slash, maintaining a standardized format.

Method-Based Redirection: Employing Rewrite Rules in NGINX

NGINX allows redirections based on specific request methods, such as POST, which can be crucial for securely handling form submissions.

if ($request_method = POST ) {
    return 301 https://example.com$request_uri;
}

This command redirects all POST requests to an HTTPS URL.

Protecting Images with NGINX Rewrite Rules

Protect your server’s resources by preventing unauthorized direct linking to your images.

location ~ .(gif|png|jpe?g)$ {
    valid_referers none blocked ~.google. ~.bing. ~.yahoo. example.com *.example.com;
    if ($invalid_referer) {
        rewrite ^/images/(.*)$ /stop-hotlinking.$1 last;
    }
}

This setup redirects requests with invalid referrers, effectively blocking hotlinking.

Enforcing Lowercase URLs for Consistency

Maintaining lowercase URLs across your site enhances consistency and prevents confusion.

location ~ [A-Z] {
    rewrite ^(.*)$ $scheme://$host$1 lowercase;
}

This command converts any uppercase URL elements to lowercase.

Handling Changes in URL Structure

Adapting to new URL structures without losing traffic or harming user experience is crucial during website updates.

server {
    listen 80;
    server_name example.com;
    
    location ~* ^/oldpath/(.*) {
        rewrite ^/oldpath/(.*)$ /newpath/$1 permanent;
    }
}

Redirects users and search engines from old to new URLs.

Creating Clean URLs for CMS Platforms

For CMS platforms relying on query strings, NGINX rewrite rules can create cleaner, more SEO-friendly URLs.

location / {
    try_files $uri $uri/ @extensionless-php;
    index index.html index.htm index.php;
}

location ~ \.php$ {
    try_files $uri =404;
}

location @extensionless-php {
    rewrite ^(/[^.]*[^/])$ $1.php last;
}

This setup transforms URLs to a more readable format, potentially improving SEO performance.

Conclusion

By creating and configuring rewrite rules in NGINX, you can optimize your URL management, improve SEO, and ensure a seamless user experience. Regularly review and test your rewrite rules to ensure they function as expected and make adjustments as needed. Mastering NGINX rewrite rules allows you to leverage the full power of NGINX for a more dynamic and responsive web server.

Leave a Comment