Implementing Apache’s force proxy flag for rewrite rules under NGINX

NGINX’s default behavior for rewrite rules (at least up to version 0.7.65) is to redirect if the replacement part begins with ‘http://’. Let me quote some info from NGINX’ wiki:

rewrite

syntax: rewrite regex replacement flag

[…]

If the replacement string begins with http:// then the client will be redirected, and any further rewrite directives are terminated.

It is important to take this into consideration while designing new rules because the behavior of the rule itself is bound to the place we are retrieving data from.

Apache does this differently since it offers a flag that can be set per rule which instructs the web server to just “proxy” the request (i.e. do not redirect, just get the response of that request in the background and send it back to the client). Taken from Apache’s site, this flag is:

proxy|P‘ (force proxy)
This flag forces the substitution part to be internally sent as a proxy request and immediately (rewrite processing stops here) put through the proxy module. You must make sure that the substitution string is a valid URI (typically starting with http://hostname) which can be handled by the Apache proxy module. If not, you will get an error from the proxy module. Use this flag to achieve a more powerful implementation of the ProxyPass directive, to map remote content into the namespace of the local server.

Note: mod_proxy must be enabled in order to use this flag.

How to implement this under NGINX

I have been able to get similar behavior under NGINX using ‘rewrite’ and ‘proxy_pass’ directives.

The following example implements a regular expression based rewrite rule serving content from domain2 to the client’s request on domain1.

server {
  listen 1.2.3.4:80;
  server_name domain1.com;

  location / {
    rewrite ^/([0-9][0-9]/[0-9][0-9]/.+)$ /example/?t=$1 last;
    proxy_pass http://domain2.com;
  }
}

Using that NGINX configuration, the client can request:

http://domain1.com/12/34/test

which will be proxied to:

http://domain2.com/example?t=12/34/test/

and served back to her “apparently” from http://domain1.com/12/34/test (i.e. there won’t be any URL redirection).


Posted

in

, ,

by

Tags:

Comments

0 responses to “Implementing Apache’s force proxy flag for rewrite rules under NGINX”

  1. niraj Avatar
    niraj

    how to set proxy flage [P] in Nginx

    In your case suppose domain2 is on the another server in that what would be the sysntax for proxy [P].

    rewrite ^/([0-9][0-9]/[0-9][0-9]/.+)$ http://domain2/example/?t=$1 last;

    above is the case in that how you would set proxy flag.