Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

nginx rewrite virtual directory to file

This should be really easy to do but I'm hitting my head on the wall. If I get a request for www.mysite.com/mypath I want to serve the content of www.mysite.com/myotherpath/thisfile.html. How can I do this with an nginx config.

like image 676
Michael Gorham Avatar asked Sep 09 '12 18:09

Michael Gorham


People also ask

What does rewrite do in nginx?

NGINX rewrite rules are used to change entire or a part of the URL requested by a client. The main motive for changing an URL is to inform the clients that the resources they are looking for have changed its location apart from controlling the flow of executing pages in NGINX.

What is return 301 in nginx?

Temporary and Permanent Nginx Redirect Explained To map this change, the redirects response code 301 is used for designating the permanent movement of a page. These kinds of redirects are helpful when the user wants to change the domain name and no longer wants a browser to access it.

What is $1 in nginx?

*$ $1/linux/$2.html break; redirect: This flag will do a temporary redirection using 302 HTTP code. This is mainly used when the replacement string is not http, or https, or $scheme.

What is $scheme in nginx?

The rewritten URL uses two NGINX variables to capture and replicate values from the original request URL: $scheme is the protocol (http or https) and $request_uri is the full URI including arguments. For a code in the 3xx series, the url parameter defines the new (rewritten) URL.


2 Answers

Use rewrite directive within proper location block. So for example you have basic location which will handle all requests

location / {
    /*your rules here*/
}

You will need to add another block, which will do for you handling of specific path

location /mypath {
    rewrite ^/mypath$ /real/path/to/file/thisfile.html; 
}

Also for your server to think in that block that thisfile.html is default you can use try thisfile.html directive

It is all well explained on official page Official Nginx RewriteModule page

like image 146
Alexey Kamenskiy Avatar answered Oct 03 '22 07:10

Alexey Kamenskiy


location = /mypath {
    try_files /myotherpath/thisfile.html =404;
}
  • http://nginx.org/r/try_files
  • http://nginx.org/r/location
like image 30
VBart Avatar answered Oct 03 '22 08:10

VBart