keepcalculator

06 Numbers and Powers

Nginx Rewrite Rules: How to Rewrite URLs

Card No. 06·73264 · Updated · Standard formula, shown below

The calculator on this card is switched off while it is checked. The formula is below, and the worked example shows how to do the sum by hand.

Nginx rewrite rules let you change a requested URL into a different one before the server processes it, using the rewrite directive or the more flexible try_files directive. You write these rules in a server or location block, and they are essential for clean URLs, redirects, and migrating old paths to new ones. This article explains how to write, test, and debug rewrite rules, with concrete examples and common pitfalls.

Background: Why Rewrite URLs?

URL rewriting is a core part of web server configuration. Without it, a site that changes its content structure would break every external link and bookmark. Rewrites also help with:

  • Clean URLs: Turning /product.php?id=42 into /product/42.
  • Redirects: Moving from HTTP to HTTPS, or from www to non-www.
  • Legacy paths: Keeping old links working after a CMS migration.
  • SEO: Consolidating duplicate content and preserving link equity.

Unlike Apache’s .htaccess, Nginx does not read per-directory config files; all rewrite rules live in the main config (nginx.conf) or in included site files. This gives better performance but requires care because a misconfigured rule can break the whole site.

How Nginx Rewrites Work

The core directive is rewrite, which takes a regular expression and a replacement string, plus an optional flag. When a request matches the regex, Nginx replaces the URL and either continues processing or restarts the search depending on the flag. The syntax is:

rewrite regex replacement [flag];

Flags you will use most often:

  • last – stops processing the current set of rewrite directives and starts a new search for the rewritten URL.
  • break – stops processing rewrite directives but does not start a new search; the rewritten URL is used as-is.
  • redirect – returns a temporary 302 redirect to the client.
  • permanent – returns a permanent 301 redirect.

For example, to redirect an old path to a new one permanently:

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

This sends a 301 to /new/anything. Without a flag, Nginx silently rewrites the URL internally, which is what you want for clean URLs that map to a backend script.

Choosing Between rewrite and try_files

Many situations that seem to require a rewrite are better handled with try_files, which checks for the existence of files and falls back to a URI. For example, a common WordPress rule is:

location / {
    try_files $uri $uri/ /index.php?$args;
}

This tells Nginx: if the file exists, serve it; if a directory exists, serve it; otherwise pass the request to index.php with the original query string. This is cleaner than a rewrite because it does not change the URL the client sees, and it avoids regex overhead.

Use rewrite when you need to change the URL itself, such as for redirects or when the backend expects a different path. Use try_files when you want a fallback for missing files, which is the typical case for front controllers and single-page applications.

Common Rewrite Examples

Here are practical rules you can adapt:

  • Force HTTPS:
    if ($scheme = http) { return 301 https://$host$request_uri; }
  • Remove trailing slash:
    rewrite ^/(.*)/$ /$1 permanent;
  • Map old query to new path:
    rewrite ^/product\.php$ /product/$arg_id last;
  • Redirect a single page:
    rewrite ^/about-us$ /about permanent;

Note that the if directive is often discouraged except for redirects; for most other logic, use a location block. Also, the $arg_id variable captures the id query parameter, so /product.php?id=42 becomes /product/42.

Testing and Debugging Rewrites

Before applying a rewrite, test your regex with a tool like pcre2test or an online regex tester that supports PCRE syntax. Nginx uses Perl-compatible regular expressions, so lookaheads are allowed but may be slow. To test the configuration, run:

nginx -t

This checks syntax but not logic. To see what a request would match, use the debug log by adding error_log /var/log/nginx/error.log debug; and then make a request. The log will show which rewrite rules were evaluated and the final URI. A common mistake is forgetting that rewrite rules inside a location block only apply to that location; if the rewritten URL matches a different location, the processing may restart, which can cause a loop if not careful.

Common Mistakes and How to Avoid Them

  • Infinite redirect loops: Often caused by a rewrite that matches the rewritten URL again. Use break or last appropriately, and test with curl -I to see the redirect chain.
  • Using if for everything: The if directive has surprising behavior in Nginx; it creates a nested request, and some directives like return work fine, but rewrite inside if can cause unexpected results. Prefer try_files or separate location blocks.
  • Not escaping special characters: In regex, a dot matches any character, so to match a literal dot use \.. For example, ^/index\.php$.
  • Forgetting the query string: By default, the query string is preserved when you rewrite, but if you want to remove it, add a ? at the end of the replacement, like rewrite ^/old$ /new? permanent;.

Rewrite vs. Redirect: What’s the Difference?

A rewrite changes the URL internally, and the client never sees the new URL. A redirect sends an HTTP response (301 or 302) telling the browser to go to a different URL. Use a rewrite when you want to serve content from a different path without changing the address bar; use a redirect when you want to permanently move a page. For SEO, a 301 redirect passes most of the link equity, while a rewrite does not change the URL at all, so it is not a redirect. Many people confuse the two; the rewrite directive with a permanent flag is actually a redirect, not a silent rewrite.

Frequently Asked Questions

How do I rewrite a URL with a query string in Nginx?

You can capture query parameters using variables like $arg_name. For example, to rewrite /search.php?q=hello to /search/hello, use rewrite ^/search\.php$ /search/$arg_q last;. The query string is preserved unless you add a ? at the end of the replacement.

What is the difference between last and break in Nginx rewrite?

last stops the current rewrite phase and starts a new search for the rewritten URI, which may match a different location block. break stops the rewrite phase and uses the rewritten URI as-is, without re-searching locations. Use last when the rewritten URL should be processed by another location; use break when you want the current location to handle the new URI.

Why is my Nginx rewrite causing a 404 error?

A 404 usually means the rewritten URI does not exist as a file and there is no fallback. Check that your rewrite points to a valid path, and that you have a try_files or a location that handles the rewritten URI. Also verify that the regex matches the exact request; test with curl and check the error log for the final URI.

Can I use regular expressions in Nginx rewrite rules?

Yes, Nginx uses PCRE (Perl Compatible Regular Expressions). You can use patterns like .*, ^, $, and capture groups with parentheses. Be careful with special characters and always escape literal dots and slashes where needed.

How do I redirect all traffic from HTTP to HTTPS with a rewrite?

The cleanest way is to use a return 301 https://$host$request_uri; in a server block that listens on port 80. Using rewrite for this is possible but less efficient; the return directive is simpler and avoids regex overhead.

What is the best way to remove the www prefix from a URL?

Create a server block for www.example.com that returns a 301 to https://example.com$request_uri. This is a redirect, not a rewrite, and it is the standard method. Avoid using a rewrite for this because it can create loops if not configured correctly.

Related

Formula used

Each line is one input (in, sel, list) or one result (out: label, unit, formula, decimals). How the calculators work

Method: the standard formula for this calculation, rounded as each result states. See how the calculators work or report an error.

More cards in this drawer

The whole Numbers and Powers drawer →