Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rewrite root address to a subdirectory in nginx

Tags:

nginx

I'm converting my mediawiki site to use nginx as a frontend for static files with apache on the backend for php. I've gotten everything working so far except for when I view the root directory "example.com" it tries to serve a directory listing and gives a 403 error since I have that disabled and don't have an index file there.

The apache rewrite rule I have in place right now is simply:

RewriteRule ^$ /wiki/Main_Page [L] 

I tried something similar with a location directive in nginx, but it's not working:

location = / {     rewrite "^$" /wiki/Main_Page; } 

The rest of my location directives are:

location / {     try_files $uri $uri/ @rewrite; }  location @rewrite {     rewrite ^/wiki/(.*)$ /w/index.php?title=$1&$args; }  location ~* \.(js|css|png|jpg|jpeg|gif|ico)$ {     try_files $uri /w/index.php?title=$1&$args;     expires max;     log_not_found off; }  location ~ \.php?$ {     proxy_set_header X-Real-IP  $remote_addr;     proxy_set_header X-Forwarded-For $remote_addr;     proxy_set_header Host $host;     proxy_pass http://127.0.0.1:8080; } 

I can simply put an index.php file with header('Location:') in it, but I'd rather just do it properly with a rewrite rule.

All the examples I've found online for running mediawiki with nginx run the wiki as wiki.example.com instead of a /wiki/ subdirectory.

Edit: I also tried adding to the try_files like this: try_files $uri $uri/ @rewrite /wiki/Main_Page; with the same 403 error result.

like image 809
Kadaan Avatar asked Jul 19 '13 04:07

Kadaan


People also ask

How do you write rewrite rules in NGINX?

The syntax of rewrite directive is: rewrite regex replacement-url [flag]; regex: The PCRE based regular expression that will be used to match against incoming request URI. replacement-url: If the regular expression matches against the requested URI then the replacement string is used to change the requested URI.

What is NGINX permanent redirect?

Permanent redirects such as NGINX 301 Redirect simply makes the browser forget the old address entirely and prevents it from attempting to access that address anymore. These redirects are very useful if your content has been permanently moved to a new location, like when you change domain names or servers.


2 Answers

I found help in the nginx irc chat.

Basically what I needed to do was use a return instead of rewrite. So I changed this:

location = / {     rewrite "^$" /wiki/Main_Page; } 

to this:

location = / {     return 301 http://www.example.com/wiki/Main_Page; } 
like image 98
Kadaan Avatar answered Sep 19 '22 07:09

Kadaan


I prefer to use:

location = / {     return 301 http://$host/wiki/Main_Page; } 
like image 28
Nicolas Roux Avatar answered Sep 23 '22 07:09

Nicolas Roux