Detailed nginx Configure URL redirection-Reverse proxy _nginx

Source: Internet
Author: User
Tags current time server port nginx reverse proxy

This article system: centos6.5_x64

Three host: Nginx Mainframe, hostname:master.lansgg.com ip:192.168.10.128
Apache Mainframe, hostname:client1.lansgg.com ip:192.168.10.129

First, Nginx address redirection

Second, Nginx reverse proxy

1, address redirection: Refers to when users browse a Web site, the user will be directed to another Web site technology. Used to turn a long string of URLs into shorter URLs. Because when you want to spread a website, often because the URL is too long, bad memory, but also because of the Internet for free web space, the Web site must be changed, uninformed users also think the site closed. Then you can use the Internet to transfer the site. This technique enables a Web page to be linked by a different Uniform Resource Locator (URL).

1.1. This module allows the use of regular expressions to rewrite URIs (requires pcre libraries) and can be redirected and selected differently depending on the dependent variables. If this instruction is specified in the Server field, it is executed before the requested location is determined, and if there are other overriding rules in the location selected after the instruction is executed, they are also executed. If this instruction is executed in location and a new URI is generated, then location again determines the new URI. Such a loop can be executed up to 10 times, exceeding the Nginx will return 500 errors

Regular expression matches, where:

* ~ to Match case sensitivity

* ~* matching for case-insensitive case

*!~ and!~* are case insensitive and case-insensitive mismatches, respectively

File and directory matching, where:

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

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

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

*-X and!-x are used to determine whether a file is executable

Flag tags are:
* Last equivalent to the [L] tag in Apache, which means complete rewrite

* Break termination match, no longer match the following rule

* REDIRECT Return 302 temporary redirect Address bar will show the address after the jump

* Permanent return 301 Permanent redirect Address bar will show the address after the jump

Some of the global variables available can be used as conditional judgments

$args, the parameters in the request;
$content _length, "content-length" in HTTP request information;
$content _type, request the "Content-type" in the information;
$document _root, set the value for the root path of the current request;
$document _uri, same as $uri;
$host, the "host" in the request information is equal to the server name set if there is no host row in the request;
$limit _rate, the limit of connection rate;
$request _method, the requested method, such as "get", "POST" and so on;
$remote _addr, client address;
$remote _port, client port number;
$remote _user, client user name, authentication;
$request _filename, the file path name of the current request
$request _body_file
$request _uri, the requested URI, with the 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, server address, if the server address is not indicated with listen, use this variable to initiate a system call to get the address (resulting in a waste of resources);
$server _name, requesting the server name to arrive;
$server _port, requesting the arrival of the server port number;
$uri, the URI of the request may be different from the original value, such as redirection.

Rewrite directive: can be used in server, location, if region;

Syntax: Rewrite regex replacement flag

Modifies the URI according to the relevant regular expression and string, and the instructions are executed in the order in which they appear in the configuration file.

You can add a tag after an overriding instruction.

If the substituted string starts with http://, the request is redirected and no more rewrite instructions are executed.

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

    • Last-completes the rewrite instruction and then searches for the appropriate URI or location.
    • Break-Complete the rewrite instruction.
    • Redirect-returns 302 temporary redirection, if the replacement field starts with a http://, it is used.
    • Permanent-Returns 301 permanent redirects.

Note If a redirect is relative (no host name part), Nginx will use the first name specified by the "host" header or the server_name directive that matches the server_name instruction during redirection, if the header does not match or does not exist, if there is no set Server_ Name, the local host name will be used, and if you always want Nginx to use the "host" header, you can use the "*" wildcard character (see server_name in the HTTP Core module) in server_name. 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, or 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 remaining request parameters are appended to the following, to prevent attaching, you can follow a question mark after the last character:

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

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

/photos/123456

For:

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

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

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

If you specify a "? "At the end of the rewrite, Nginx will discard the arguments in the request, that is, the variable $args, which can be used at the end of the rewrite when using the $request_uri or $uri& $args"? "To avoid nginx processing of two-time argument strings.

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, overrides only operate on paths, not parameters, and if you want to override 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 is not compiled and is different from the URI in the location process (refer to the location in the HTTP core module)

Example: When accessing www.lansgg.com, jump to www.Aries.com;

 server {
  listen 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/;
  }

The break instruction can use the server, location, if region, abort Rewirte, not continue the match

Last instruction can be server, location, if region;

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 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, directly initiate the request www.lansgg.com/c1.html, he will display the C2 content;


Using last, you will continue to search for the following location that meet the criteria (conforming to the rewritten/c2.html request). At this point,/c2.html just corresponds to the surface location conditions, into the curly braces {} code execution, here will return 508.

 server {
 listen 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
 }}
 

Use Firebug can be seen;

If instruction can use server, location area;

Example: When accessing the http://www.lansgg.com URL, jump to www.Aries.com;

 server {
  listen 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;
  }
  }

The return instruction can use the server, location, if region

Syntax: Return code

This instruction ends the execution of the configuration statement and returns the status code for the client, using the following values: 204,400,402-406,408,410, 411, 413, 416, and 500-504. In addition, nonstandard code 444 closes the connection and does not send any headers.

Rewrite_log directives can use the server, location, if region

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

The set directive can use the server, location, or if region

Syntax: Set Variable Value

Directive sets a variable and assigns it a value that can be text, variables, and their combination.

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

Uninitialized_variable_warn directives can use HTTP, server, location, if region

Syntax: Uninitialized_variable_warn on|off

Default value: Uninitialized_variable_warn on

Turns on or off logging of warning logs in uninitialized variables.

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

Expires directives can be HTTP, server, location area

Syntax: Expires [Time|epoch|max|off]

Default value: Expires off

This directive controls the headers of the "Expires" and "Cache-control" in the HTTP answer (plays a role in controlling the page cache). You can use a positive or negative number in a time value. The value of the "Expires" header will be obtained by the current system time plus the set duration value.

EPOCH specifies that the value of "Expires" is 1 January, 1970, 00:00:01 GMT.

MAX Specifies the value of "Expires" to December 2037 23:59:59 GMT, and the value of "Cache-control" is 10 years.

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

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

Negative Number: Cache-control:no-cache

Positive or 0: Cache-control:max-age = #, # is the number of seconds in a specified time S. Other units have D (days), H (Hours)

"Off" means not modifying values for "Expires" and "Cache-control"

Control pictures such as expiration time is 30 days, this time can be set longer. Depending on the circumstances

Location ~ \. (Gif|jpg|jpeg|png|bmp|ico) $ {
   log_not_found off; #不记录404 not found error log   expires 30d;
   break;  

Controls matching/resource/or/mediatormodule/all file cache settings to the maximum time

  Location ~/(Resource|mediatormodule)/{
    root/opt/demo;
    Expires Max;
  }

Sets the expiration time for a file; This is 600 seconds, and the access log is not logged

Location ^~/html/scripts/loadhead_1.js {
access_log off;
Root/opt/lampp/htdocs/web;
Expires;
break;

Set gzip

Under normal circumstances compressed HTML, CSS, JS, PHP, jhtml and other documents, the size can be reduced to the original 25%, that is, the original 100k of HTML, compressed only 25k left. This will undoubtedly save a lot of bandwidth, but also reduce the load on the server.

Configuring Gzip in Nginx is easier

In general, just add the following lines to the nginx.conf HTTP segment

 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 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 F Iles

Access HTTP://WWW.LANSGG.COM/C will jump to http://www.lansgg.com/cc

302 is a temporary redirect;

Permanent redirection (implied redirection)

Edit nginx.conf

 server {
  listen 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;
  }

Access to the http://www.lansgg.com/c/page shows the page after the jump, but the URL has not changed; Firebug also see no 302 code information; now it is 301;

2, Reverse proxy: Refers to the proxy server to accept connection requests on the Internet, and then forward the request to the internal network of the server, and the results from the server returned to the Internet requesting the connection of the client, at this time the proxy server performance as a server.

2.1, configure Nginx to achieve reverse proxy;

Requirements: Access Http://192.168.10.128/other to return index.html in the Apache host's other directory

involves Nginx directives:

Syntax: Proxy_pass URL

Fields can be used: location, location if fields

This instruction sets the address of the proxy server and the mapped URI, and the address can be in the form of a host name or IP port number, for example: Proxy_pass http://192.168.10.129/url

2.2. Configure Nginx configuration file nginx.conf

 server {
 listen 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. Configure CLIENT1

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

2.4, testing;

Visit Url:http://www.lansgg.com/other you'll find jump to: http://192.168.10.129/other/

To 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 "-" "mozilla/5.0 (Windows NT 6.1; WOW64; rv:32.0) gecko/20100101 firefox/32.0 "

The above is the entire content of this article, I hope to help you learn, but also hope that we support the cloud habitat community.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.