Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to configure url redirection for nginx

2025-01-19 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >

Share

Shulou(Shulou.com)05/31 Report--

Most people do not understand the knowledge points of this article "nginx how to configure url redirection", so the editor summarizes the following content, detailed content, clear steps, and has a certain reference value. I hope you can get something after reading this article. Let's take a look at this "nginx how to configure url redirection" article.

The system of this paper: centos6.5_x64

Three hosts: nginx host, hostname: master.lansgg.com ip: 192.168.10.128

Apache host, hostname: client1.lansgg.com ip: 192.168.10.129

I. nginx address redirection

II. Nginx reverse proxy

1. Address redirection: a technique that directs a user to another web site when he or she is browsing one URL. It is often used to convert a long list of web addresses into shorter ones. At this point, you can use the re-address on the network. This technology enables a web page to be linked by different uniform resource locators (url).

1.1.This module allows you to rewrite uri using regular expressions (pcre library is required), and you can redirect and select different configurations based on related variables. If this instruction is specified in the server field, it will be executed before the requested location is determined, and if there are other rewriting rules in the selected location after instruction execution, they will also be executed. If executing this instruction in location results in a new uri, then location once again determines the new uri. Such a loop can be executed up to 10 times, after which nginx will return 500 errors.

Regular expressions match, where:

* ~ for case-sensitive matching

* ~ * for case-insensitive matching

*! ~ and! * are case-sensitive mismatch and case-insensitive mismatch, respectively

File and directory match, where:

*-f and!-f are used to determine whether a file exists.

*-d and!-d are used to determine whether a directory exists.

*-e and!-e are used to determine whether a file or directory exists

*-x and!-x are used to determine whether the file is executable or not

The flag tags are:

* last is equivalent to the [l] tag in apache, indicating that the rewrite is completed

* break terminates the match and no longer matches the following rules

* redirect returns 302 temporary redirect address column will display the address after the jump

* the address bar returned by permanent for permanent redirection will display the address after the jump

Some of the available global variables are, which can be used for conditional judgment.

$args, parameter in the request; $content_length, "content-length" in the http request message; $content_type, "content-type" in the request message; $document_root, set for the root path of the current request; $document_uri, the same as $uri; $host, "host" in the request message, if there is no host line in the request, equal to the server name set; $limit_rate, limit on the connection rate $request_method, request method, such as "get", "post", etc.; $remote_addr, client address; $remote_port, client port number; $remote_user, client user name, authentication; $request_filename, current requested file path name $request_body_file$request_uri, requested uri, with query string; $query_string, same as $args $scheme, the protocol used, such as http or https, such as rewrite ^ (. +) $scheme://example.com$1 redirect;$server_protocol, the requested protocol version, "http/1.0" or "http/1.1"; $server_addr, the server address. If the server address is not specified with listen, using this variable will initiate a system call to obtain the address (resulting in a waste of resources) $server_name, the name of the server on which the request arrives; $server_port, the server port number on which the request arrives; and $uri, the uri of the request, which may be different from the original value, such as redirected.

Rewrite directive: can be used in server, location, if areas

Syntax: rewrite regex replacement flag

Modify the uri according to the relevant regular expressions and strings, and the instructions are executed in the order in which they appear in the configuration file.

You can add a tag after the rewrite instruction.

If the replacement string begins with http://, the request is redirected and redundant rewrite instructions are no longer executed.

The tail tag (flag) can be the following values:

Last-complete the rewrite instruction and then search for the appropriate uri or location.

Break-complete the rewrite instruction.

Redirect-returns 302 temporary redirection, which is used if the replacement field begins with http://.

Permanent-returns 301 permanent redirection.

Note if a redirect is relative (there is no hostname part), nginx will use the "host" header that matches the server_name instruction or the first name specified by the server_name directive during the redirect. If the header does not match or does not exist, if server_name is not set, the local hostname will be used, if you always want nginx to use the "host" header. You can use the "*" wildcard in server_name (see server_name in the http core module). For example:

Rewrite ^ (/ download/.*) / media/ (. *)\.. * $$1/mp3/$2.mp3 last;rewrite ^ (/ download/.*) / audio/ (. *)\.. * $$1/mp3/$2.ra last;return 403

But if we put it in a location named / download/, we need to change the last tag to break, otherwise nginx will execute 10 loops and return 500 errors.

Location / download/ {rewrite ^ (/ download/.*) / media/ (. *)\.. * $1/mp3/$2.mp3 break; rewrite ^ (/ download/.*) / audio/ (. *)\. * $1/mp3/$2.ra break; return 403;}

If the replacement field contains parameters, the rest of the request parameters are appended, and to prevent them, you can follow the last character with a question mark:

Rewrite ^ / users/ (. *) $/ show?user=$1? Last

Note: curly braces ({and}) can be used in both regular expressions and configuration blocks. To prevent conflicts, regular expressions need double quotes (or single quotes) to use curly braces. For example, to rewrite the following url:

/ photos/123456

Are:

/ path/to/photos/12/1234/123456.png

The following regular expression is used (note the quotation marks):

Rewrite "/ photos/ ([0-9] {2}) ([0-9] {2}) ([0-9] {2})" / path/to/photos/$1/$1 $2 Universe 1 $2 $3.png

If you specify a "?" At the end of the rewrite, nginx discards the parameter in the request, the variable $args, and you can use "?" at the end of rewrite when using $request_uri or $uri&$args. To prevent nginx from processing parameter strings twice.

Use $request_uri in rewrite to rewrite www.example.com to example.com:

Server {server_name www.example.com; rewrite ^ http://example.com$request_uri? Permanent;}

Similarly, rewriting operates only on paths, not parameters, and if you want to rewrite a url with parameters, you can use the following instead:

If ($args ^ ~ post=100) {rewrite ^ http://example.com/new-address.html? Permanent;}

Note that the $args variable will not be compiled, unlike uri in the location process (see location in the http core module)

Example: jump to www.aries.com when accessing www.lansgg.com

Server {listen 80 default_server; server_name www.lansgg.com lansgg.com; access_log logs/lansgg.access.log main; error_log logs/lansgg.error.log; root / opt/nginx/nginx/html/lansgg; index index.html; rewrite ^ / http://www.aries.com/;}

Break instruction can use server, location, if region; abort rewirte, no longer continue matching

Last instructions can be used in server, location, if areas

The difference between last and break is that last does not stop matching the following location.

Test the difference between break and last

Server {listen 80 default_server; server_name www.lansgg.com lansgg.com; access_log logs/lansgg.access.log main; error_log logs/lansgg.error.log; root / opt/nginx/nginx/html/lansgg; index index.html; location / c1.html {rewrite / c1.html / c2.html break;} location / c2.html {return 508 }} [root@master sbin] # echo "C1" > / opt/nginx/nginx/html/lansgg/c1.html [root@master sbin] # echo "c2" > / opt/nginx/nginx/html/lansgg/c2.html

Using break will stop matching the following location, initiate the request directly, and it will display the contents of c2.

If you use last, the search continues to see if there is a location below that meets the criteria (matching the rewritten / c2.html request). At this point, / c2.html corresponds to the condition of face location and executes the code in curly braces {}, which returns 508.

Server {listen 80 default_server; server_name www.lansgg.com lansgg.com; access_log logs/lansgg.access.log main; error_log logs/lansgg.error.log; root / opt/nginx/nginx/html/lansgg; index index.html; location / c1.html {rewrite / c1.html / c2.html last;} location / c2.html {return 508;}}

Using firebug, you can see

The if instruction can use server, location area

Example: jump to www.aries.com when visiting a URL

Server {listen 80 default_server; server_name www.lansgg.com lansgg.com; access_log logs/lansgg.access.log main; error_log logs/lansgg.error.log; root / opt/nginx/nginx/html/lansgg; index index.html; if ($http_host = www.lansgg.com) {rewrite (. *) http://www.aries.com;}}

Return instructions can use server, location, if areas

Syntax: return code

This instruction ends the execution of the configuration statement and returns the status code for the client. You can use the following values: 204400402-406, 408, 410,411,413,416 and 500,504. In addition, non-standard code 444 closes the connection and does not send any headers.

Rewrite_log instructions can use server, location, if areas

When enabled, the rewrite log of the notice tag is recorded in error log.

Set instructions can use server, location, if areas

Syntax: set variable value

Directive sets a variable and assigns a value to it, which can be text, variables, and a combination of them.

You can use set to define a new variable, but you cannot use set to set the value of the $http_xxx header variable.

Uninitialized_variable_warn instructions can use http, server, location, if areas

Syntax: uninitialized_variable_warn on | off

Default value: uninitialized_variable_warn on

Turns warning logging on or off in uninitialized variables.

In fact, the rewrite directive is compiled into internal code when the configuration file is loaded and is used when the interpreter makes a request.

Expires instructions can be used in http, server, location areas

Syntax: expires [time | epoch | max | off]

Default value: expires off

This directive controls the headers of "expires" and "cache-control" in the http response (which controls the page cache). You can use positive or negative numbers in the time value. The value of the "expires" header will be obtained by the current system time plus the set time value.

Epoch specifies that the value of "expires" is 1 january, 1970, 00:00:01 gmt.

Max specifies a value of 31 december 2037 23:59:59 gmt for "expires" and 10 years for "cache-control".

-1 specifies that the value of "expires" is the current time of the server-1s, that is, it expires forever

The value of the "cache-control" header is determined by the specified time:

Negative number: cache-control: no-cache

Positive or zero: cache-control: max-age = #, # is the number of seconds at a specified time. Other units are d (days), h (hours)

"off" means that the values of "expires" and "cache-control" are not modified

Control the expiration time of pictures, etc., to 30 days, which can be set longer. It depends on the situation.

Location ~\. (gif | jpg | jpeg | png | bmp | ico) ${log_not_found off; # do not record 404 not found error log expires 30d; break;}

Controls the maximum time for all file caches in matching / resource/ or / mediatormodule/ to be set

Location ~ / (resource | mediatormodule) / {root / opt/demo; expires max;}

Set the expiration time of a file; here it is 600 seconds, and no access log is recorded.

Location ^ / html/scripts/loadhead_1.js {access_log off;root / opt/lampp/htdocs/web;expires 600

Set up gzip

In general, the size of compressed html, css, js, php, jhtml and other files can be reduced to 25% of the original, that is, the original 100k html has only 25k left after compression. This will undoubtedly save a lot of bandwidth and reduce the load on the server.

It is easy to configure gzip in nginx

In general, you only need to add the following lines to the http section of nginx.conf.

Gzip on; gzip_min_length 1000; gzip_buffers 48k; gzip_types text/plain application/x-javascript text/css text/html application/xml

You can use the web page gzip detection tool to detect whether a web page has gzip enabled

Temporary redirect example: access www.lansgg.com/c redirect to www.lansgg.com/cc

Edit nginx.conf

Server {listen 80 default_server; server_name www.lansgg.com lansgg.com; access_log logs/lansgg.access.log main; error_log logs/lansgg.error.log; root / opt/nginx/nginx/html/lansgg; index index.html; rewrite ^ / c / (. *) $http://www.lansgg.com/cc/$1; } [root@master lansgg] # tree. ├── c │ └── index.html ├── cc │ └── index.html ├── index.html └── it.jpg 2 directories, 4 files

Access to http://www.lansgg.com/c will jump to http://www.lansgg.com/cc

302 is a temporary redirection.

Permanent redirection (implied redirection)

Edit nginx.conf

Server {listen 80 default_server; server_name www.lansgg.com lansgg.com; access_log logs/lansgg.access.log main; error_log logs/lansgg.error.log; root / opt/nginx/nginx/html/lansgg; index index.html; rewrite ^ / c / (. *) $/ cc/$1;}

Visiting the http://www.lansgg.com/c/ page shows the jumped page, but the url has not changed; firebug does not see the 302 code information; now it is actually 301

2. Reverse proxy: it means that the proxy server accepts the connection request on the internet, then forwards the request to the server on the internal network, and returns the result from the server to the client requesting the connection on the internet. At this time, the proxy server behaves as a server externally.

2.1.Configuring nginx to implement reverse proxy

Requirement: access the index.html under the other directory of the apache host returned by http://192.168.10.128/other

The nginx instruction is involved:

Syntax: proxy_pass url

Available fields: location, if field in location

This directive sets the address of the proxy server and the mapped uri, which can be in the form of hostname or ip plus port number, for example: proxy_pass http://192.168.10.129/url

2.2.Configuring nginx profile nginx.conf

Server {listen 80 default_server; server_name www.lansgg.com lansgg.com; access_log logs/lansgg.access.log main; error_log logs/lansgg.error.log; root / opt/nginx/nginx/html/lansgg; location / {index index.html;} location / other {proxy_pass http://192.168.10.129/other; proxy_set_header x-real-ip $remote_addr;}}

2.3.Config client1

Mkdir / var/www/html/otherecho "192.168.10.129" > / var/www/html/other/index.html

2.4. Testing

Visit url: http://www.lansgg.com/other and you will find that you have jumped to: http://192.168.10.129/other/

View the log:

[root@client1] # tail-f / var/log/httpd/access_log 192.168.10.1-- [06/nov/2014:21:25:44 + 0800] "get / other/ http/1.1" 20015-"" mozilla/5.0 (windows nt 6.1; wow64) Rv:32.0) gecko/20100101 firefox/32.0 "above is the content of this article about" how to configure url redirection in nginx ". I believe you all have some understanding. I hope the content shared by the editor will be helpful to you. If you want to learn more about related knowledge, please follow the industry information channel.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Internet Technology

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report