nginx rewrite url from one site to subdomain in other site

June 14, 2018 958 views
Nginx CentOS

how can i rewrite or redirect url[0]=index&tmplname[0]=msiteindex2&tmplinto[1]=middle&tmplname[1]=muserlogin_middle to ?

I have tried to match url but no effect. simple redirec 301 doesnt work.

1 Answer

Hi @DariusNez,

You can use the return or rewrite Directive

The return Directive

Here’s a very simple example that redirects clients to a new domain name:

server {
    listen 80;
    listen 443 ssl;
    return 301 $scheme://$request_uri;

The listen directives mean the server block applies to both HTTP and HTTPS traffic. The server_name directive matches request URLs that have domain name www.old‑ The return directive tells NGINX to stop processing the request and immediately send code 301 (Moved Permanently) and the specified rewritten URL to the client.

The rewrite Directive

Like the return directive, you enclose the rewrite directive in a server or location context that defines the URLs to be rewritten. Otherwise, the two directives are rather more different than similar, and the rewrite directive can be more complicated to use correctly. Its syntax is simple enough:

rewrite regex URL [flag];

But the first argument, regex, means that NGINX Plus and NGINX rewrite the URL only if it matches the specified regular expression (in addition to matching the server or location directive). The additional test means NGINX must do more processing.

Here’s a sample NGINX rewrite rule that uses the rewrite directive. It matches URLs that begin with the string /testing and then include the /newtest/ or /oldtest/ directory somewhere later in the path. It replaces those elements with /mp3/ and adds the appropriate file extension, .mp3 or .ra. The $1 and $2 variables capture the path elements that aren’t changing. As an example, /download/cdn-west/media/file1 becomes /download/cdn-west/mp3/file1.mp3. If there is an extension on the filename (such as .flv), the expression strips it off and replaces it with .mp3.

server {
    # ...
    rewrite ^(/testing/.*)/newtest/(\w+)\.?.*$ $1/mp3/$2.mp3 last;
    rewrite ^(/testing/.*)/oldtest/(\w+)\.?.*$ $1/mp3/$2.ra  last;
    return  403;
    # ...

Having said that much, I’ll recommend using the last mentioned method to get the results you need


Have another answer? Share your knowledge.

You can type !ref in this text area to quickly search our full set of tutorials, documentation & marketplace offerings and insert the link!