URL Rewrite
Nginx’s **URL Rewrite (Rewrite)** function allows you to dynamically modify the request path or redirect according to the requested URL. By rewriting the URL, you can implement such as:
- Friendly URL: Convert complex URLs to simple and easy to remember.
- 301/302 Redirect: Implement permanent or temporary redirection of the page.
- Conditional rewrite: Modify the request path based on different conditions (such as request header, IP address, user agent, etc.).
This article will introduce in detail how to implement URL rewriting in Nginx and give some common practical scenarios.
URL rewrite directive in Nginx
URL rewriting in Nginx mainly depends on two directives:
-
rewrite
: The URL used to modify the request. -
try_files
: Try a series of file paths and override the URL if the file does not exist.
rewrite command
The rewrite directive allows you to rewrite URLs based on regular expressions. The basic syntax is as follows:
rewrite <Matching rules> <Rewrite the target> [Logo];
Matching rules: Regular expression, matching the requested URL.
Rewrite the target: New URL. When complying with the rules, Nginx will rewrite the requested URL to this target.
-
Logo(Optional): Controls the behavior of rewriting. Common flags include:
last
: means to re-search for a new location block (that is, continue to match the new rules).break
: Stop the rule matching in the current location block and execute subsequent instructions.redirect
: Perform temporary redirection (302).permanent
: Perform permanent redirect (301).
Here is an example:
rewrite ^/archive/(\d{4})/(\d{2})/(\d{2})$ /archive?year=$1&month=$2&day=$3 last;
It can be decomposed into:
-
^/archive/(\d{4})/(\d{2})/(\d{2})$
: This is a regular expression that indicates a match/archive/
The URL followed by the year, month and date. Specific match:-
^
Indicates the beginning of the matching URL; -
/archive/
is a fixed path part; -
(\d{4})
Match 4 digits (year); -
(\d{2})
Match 2 digits (month); -
(\d{2})
Match 2 digits (date); -
$
Indicates the end of the matching URL.
-
-
/archive?year=$1&month=$2&day=$3
: This is the target URL after rewriting. Here is a replacement for the capture group:-
$1
replaced with the first capture group (i.e., year). -
$2
replaced with the second capture group (i.e. month). -
$3
replaced with the third capture group (i.e. date). - The final rewritten URL is
/archive?year=2024&month=03&day=25
。
-
-
last
: This flag indicates that Nginx will stop the currentrewrite
Match and continue to rematch the requested new URL (i.e./archive?year=2024&month=03&day=25
)。
First, let’s look at this part of the regular expression:
(\d{4})/(\d{2})/(\d{2})
。
(\d{4})
:
\d
is a regular expression metacharacter that indicates a matchNumber characters, that is, any number 0-9.{4}
It is a quantifier, indicating the previous expression (here is\d
) Must appear4 times。- therefore,
(\d{4})
Match4 digits, usually used to represent year (such as 2024)./(\d{2})
:
- Similarly,
(\d{2})
Match2 digits, usually used to represent the month (such as03
) or date (such as25
)。- Here
\d{2}
The matching is 2 numbers representing the month or date./(\d{2})
:
- This part is the same as above, and the matching is2 digits, usually represents the date part.
To sum up:
(\d{4})/(\d{2})/(\d{2})
It is used to match images/2024/03/25
Such a URL, specifically:
- Part One
(\d{4})
Match the year part (e.g. 2024).- Part 2
(\d{2})
Match the month part (e.g. 03).- Part 3
(\d{2})
Match the date part (e.g. 25).
()
Function:Brackets
()
Used forCapture matching content. The captured content can be passed$1
,$2
,$3
Come to quote. This is the "capture groups" in the regular expression.In the example,
(\d{4})
、(\d{2})
and(\d{2})
It is a capture group that captures year, month and date respectively.
$1
、$2
、$3
What does it mean?In a regular expression, capture the group (i.e.
()
The matching content in ) will be assigned numerical identification in order.
$1
: Reference the first capture group (here is(\d{4})
), that is, the year part.$2
: Reference the second capture group (here is(\d{2})
), that is, the month part.$3
: Reference the third capture group (here is(\d{2})
), that is, the date part.Assume that the requested URL is
/archive/2024/03/25
,existrewrite
Instructions,(\d{4})
Will be captured2024
,(\d{2})
Captured03
, another(\d{2})
Captured25
。
$1
that is2024
(first capture group).$2
that is03
(Second Capture Group).$3
that is25
(Third Capture Group).
try_files directive
try_files is used to check whether a series of files exists, and continue processing if it exists, otherwise URL rewrite is performed. It is often used for processing static resources, such as checking whether a file exists, and if it does not exist, rewrite the request to a certain page (usually the home page or the error page).
try_files <document1> <document2> ... <Rewrite the target>;
Common URL rewrite scenarios
Implement 301/302 redirection
When you need to redirect the old URL to the new URL,rewrite
Instructions are very useful. 301 is a permanent redirect, telling the search engine that the page has been moved permanently; 302 is a temporary redirect, indicating that the page will be temporarily moved to the new URL.
Example:/old-page
Redirect to/new-page
server { listen 80; server_name ; location /old-page { rewrite ^/old-page$ /new-page permanent; } location /new-page { # Process the configuration of new pages } }
Configuration explanation:
-
rewrite ^/old-page$ /new-page permanent;
:Will/old-page
Redirect to/new-page
, and use permanent redirection (301). -
permanent
The flag indicates that this is a permanent redirect.
Redirect non-www domain names to www domain names
If you want all requests to passAccess, you can use Nginx to redirect requests for non-www domain names.
Example:Redirect to
server { listen 80; server_name ; # Perform 301 redirects return 301 $request_uri; } server { listen 80; server_name ; location / { # Normal site configuration } }
Configuration explanation:
-
return 301 $request_uri;
: AllRedirected to
, and retain the requested URI.
URL Regular Rewrite: Simplify URL Structure
You can rewrite the URL using regular expressions to make the URL more concise and SEO-compliant.
Example:/category/id/123
Rewrite as/category/123
server { listen 80; server_name ; location /category/id/ { rewrite ^/category/id/(\d+)$ /category/$1 last; } }
Configuration explanation:
-
rewrite ^/category/id/(\d+)$ /category/$1 last;
:Will/category/id/123
Rewrite as/category/123
, and uselast
The logo continues to match the new onelocation
piece.
Dynamic URL rewrite: Parameterized query
If your website URL needs to support dynamic query parameters, you can userewrite
Directives are rewritten based on URL parameters.
Example:/search?q=keyword
Rewrite as/search/keyword
server { listen 80; server_name ; location /search { rewrite ^/search\?q=(\w+)$ /search/$1 last; } }
Configuration explanation:
-
rewrite ^/search\?q=(\w+)$ /search/$1 last;
:Will/search?q=keyword
Rewrite as/search/keyword
, and uselast
The logo continues to match the new onelocation
piece.
404 Page Redirection
When the requested file or page does not exist, you may want to redirect the request to a custom 404 page or home page. Can be passedtry_files
Instruction implementation.
Example: Redirect to
server { listen 80; server_name ; location / { try_files $uri $uri/ /; } }
Configuration explanation:
-
try_files $uri $uri/ /;
:Nginx will first check whether the requested file exists. If it does not exist, the request will be rewrited as/
。
Dynamic URL rewrite in combination with regular expressions
Nginx supports powerful regular expression matching capabilities, which can be used to handle more complex URL rewrite requirements. Here is a more complex example of URL rewriting that combines conditions and regular expressions for dynamic routing.
Example: Rewrite URL based on date
server { listen 80; server_name ; location /archive/ { rewrite ^/archive/(\d{4})/(\d{2})/(\d{2})$ /archive?year=$1&month=$2&day=$3 last; } }
Configuration explanation:
- rewrite ^/archive/(\d{4})/(\d{2})/(\d{2})$ /archive?year=$1&month=$2&day=$3 last;: Rewrite /archive/2024/03/25 to /archive?year=2024&month=03&day=25.
The above is the detailed content of implementing URL rewriting and redirection in Nginx. For more information about Nginx URL rewriting and redirection, please follow my other related articles!