How to prevent rewrite after deny - nginx

I have a website inside "/directory/", and a special variation of the website inside "/directory/subdirectory/" which should only be accessible by a few specific IP addresses. The subdirectory, however is a virtual URL, the website code is still in the parent directory called "directory" in this example. So I need rewrites.
This is the relevant part of my current nginx config file:
location /directory {
# here are various rewrites for my website
location /directory/subdirectory/ {
allow 10.0.0.0/8; # example range of IP addresses allowed
deny all; # disable access for others
rewrite ^/directory/subdirectory/(.*)$ /directory/$1 last; # the website location is still in the parent folder but the PHP code knows this specific version is to be used when the user surfs into subdirectory, which is why there is this rewrite
}
try_files $uri $uri/ /directory/index.php?q=$uri&$args;
}
location ~ \.php$ {
fastcgi_split_path_info ^(.+\.php)(/.+)$;
fastcgi_pass unix:/var/run/php5-fpm.sock;
fastcgi_index index.php;
include fastcgi.conf;
fastcgi_read_timeout 43200;
}
The problem I'm facing: I don't know how to stop the execution as soon as the "deny all" hits. If you're surfing into the subdirectory, the rewrite always executes, no matter if your IP is allowed or not by the directives above it. So someone surfing to the subdirectory with an IP address which is not allowed can see the website inside subdirectory, which is of course not what I want. If I comment out the rewrite, then the allow/deny directives work as they are supposed to.
So: how can I specify this rewrite is ONLY to be executed if the visitor is not denied?
Tried adding "error_page 403 /403.html;" to that location after the "deny all;" directive but it only changes the 403 page (and can only be seen again when commenting the rewrite rule in the subdirectory). Been searching the net for days already with various search terms to make this happen, and been fiddling with variations of the config, but to no avail.
Also: the "deny all" doesn't work anymore as soon as I surf to an URL inside subdirectory, ending with ".php". I assume it is because of the "location ~ .php$" directive, getting priority for some reason over the nested location directives above. I could get around this by doing:
location ^~ /directory/subdirectory/ {
allow 10.0.0.0/8; # example range of IP addresses allowed
deny all; # disable access for others
rewrite ^/directory/subdirectory/(.*)$ /directory/$1 last;
}
location /directory {
# here are various rewrites for my website
try_files $uri $uri/ /directory/index.php?q=$uri&$args;
}
location ~ \.php$ {
fastcgi_split_path_info ^(.+\.php)(/.+)$;
fastcgi_pass unix:/var/run/php5-fpm.sock;
fastcgi_index index.php;
include fastcgi.conf;
fastcgi_read_timeout 43200;
}
Now the "location ^~ /directory/subdirectory/" directive gets priority over the "location ~ .php$" directive which makes the "deny all" work but I don't know if that's the way to go since it doesn't seem like the most "clear to read" solution because I move something from within the "directory/" location out of that location block. And also, that still doesn't solve my main problem (only making the "rewrite ^/directory/subdirectory/(.*)$ /directory/$1 last;" execute for allowed IP addresses and not those getting denied by the "deny all".
Thank you.

The issue you are facing is related to the precedence/order in which nginx handles it's directives. A detailed explanation can be found here (hats off to the author!):
In their execution order the phases are post-read, server-rewrite,
find-config, rewrite, post-rewrite, preaccess, access, post-access,
try-files, content, and finally log
Since "rewrite" comes before "access", the "rewrite" directive is handled first.
Since "if" is handled in "rewrite"-phase as well, one could write:
location ~ \.php$ {
if ($remote_addr != "172.17.0.1") {
return 403;
}
rewrite ^ /your-redirect last;
}

Related

rewrite rules for nginx and Codeigniter

I have implemented a php application in codeigniter and now want to deploy it to the nginx server. Before deploying I checked my nignx configuration on my localhost using MAMP server. It is working correctly. But, this configuration is not working on the live server. As a beginner in nginx, I am not understanding where is the mistake here. In live server, I can not write in the main nginx.conf file. I have a separate configuration file like "abc" for my application "abc". And all my application files are under "abc/xyz" directory. Here is my sample confuguration,
location /abc {
root /srv/www/htdocs/apps/;
index index.html index.htm index.php;
location /xyz {
try_files $uri $uri/ /abc/xyz/index.php;
}
location ~ \.php(\/(\w+))*$ {
try_files $uri =404;
rewrite (.+)\.php(\/(\w+))*$ $1.php break;
include /etc/nginx/fastcgi_params;
fastcgi_index index.php;
fastcgi_pass unix:/var/run/php-fpm.sock;
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
}
}
Here, I can see my welcome page https://myapplication/abc/xyz. But if I want to navigate other pages like https://myapplication/abc/xyz/other_pages, it is showing "404 Page not found". I have checked the other solutions but none of them is not working in this case. Thanks in advance for the help!
The location /xyz block is nested within the location /abc block. The nested block is required to precess URIs with a prefix of /abc/xyz.
If there are other regular expression location blocks surrounding your location /abc block, you should use the^~` modifier.
For example:
location ^~ /abc {
...
location /abc/xyz {
...
}
...
}
See this document for more.
Sorry for the late answer. It was actually very silly mistake. My controller page name was in small character. This is why it was not working. My configuration is okay. The first letter of the controller page should be in capital character. For example, my controller name is Home. So my php file name must be Home.php not home.php.

Conditional rewriting, how to manage PHP scripts?

I need to create an API gateway that I can't test... But the problem is about manage PHP scripts.
What I need
all files HTML or PHP
special names as my1 and issn redirect to localhost at port 2018
special names as my2 and my3 redirect to ETC.php
Explanation
Pseudocode with details of "What I need",
if ($uri exists) {
if extension is .php use it with php7.0-fpm.sock
else use it as static page;
} else
try the #proxy_rewrite_engine;
#proxy_rewrite_engine =
if (regex ^\(my[23])$ use
ETC.php;
elseif (regex ^/(\d+)/my1$ use
http://127.0.0.1:2018?type=int&val=$1
elseif ^/([0-9]+\-\d+[Xx]?)/issn$ use
http://127.0.0.1:2018?type=str&val=$1
else
say error;
What I try
My problematic solution, please show a real solution, translating the "Explanation" section into concrete and correct NGINX script code.
... Below, my wrong-NGINX-script for clues and inspiration, it is not the solution... Need to use if instead neasted location? The fastcgi_param is valid? Can I group locations?
server {
server_name test.mytest.news;
root /var/www/test;
index index.php index.html index.htm;
location / {
try_files $uri $uri/ #proxy;
}
location ~ \.php$ {
try_files $uri =404;
include /etc/nginx/fastcgi.conf; # without SCRIPT_FILENAME
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
fastcgi_pass unix:/run/php/php7.0-fpm.sock;
}
location #proxy {
rewrite ^\?(my[23])$ $document_root/ETC.php?cmd=$1
last;
rewrite ^/(\d+)/my1$ ?type=int&val=$1
break;
rewrite ^/([0-9]+\-\d+[Xx]?)/issn$ ?type=str&val=$1
break;
proxy_pass http://127.0.0.1:2018;
}
include snippets/ssl-test.mytest.news.conf;
} #end server
NOTE for #cnst comment: Suppose that what I need when say "all files HTML or PHP" = the try_files must to try other files tham index.htm, can be folders, imagens and other files.
If the desire is to have "a script 100% reliable, by its construction (not by testing)", then putting multiple independent issues in a single question is probably not the best approach.
Your rationale behind having to check existence of files prior to passing the request to a separate backend is not entirely clear, especially if the request is matching a given regular expression, like issn$. Best approach would be to use separate location directives for each distinct handling of the case.
More specifically, the following is also wrong with your approach: the regular expression in rewrite ^\?(my[23])$ is unlikely to match any request, as all external requests start with a slash.
Likewise, as per https://serverfault.com/a/864778/110020, the replacement string in rewrite ^/(\d+)/my1$ ?type=int&val=$1 is unlikely to be correct; in fact, when I've tried your code as above, the following is the 500 Internal Server Error I've gotten, as per nginx/error.log:
2017/07/24 08:46:22 [error] 45776#0: *2 the rewritten URI has a zero length, client: 127.0.0.1, server: , request: "GET /44444/my1 HTTP/1.1", host: "localhost:
This happens because you indeed rewrite URI to become an empty one — the question mark, ?, and anything after it, is generally not part of URI in request processing within nginx, so, as such, the URI is indeed entirely empty. Solution: at least put a slash in front of ? (i.e., /?id=), or, better yet, a full name of the script that must be activated (especially since this is merely an internal redirect).
Nginx works good with large configs. Bad idea optimize nginx.conf.
Do it simple, it'll work hard:)
I think config like this will work fine:
# Try to load existing files
location / {
try_files $uri $uri/ #rewriteIt;
}
# Handle all requests except two other locations below
location #rewriteIt {
# Send it to index.php
rewrite ^(.*)$ /index.php?cmd=$1 last;
}
# This RegExp location will rewrite to ETC.php
# It is more priority, than "/" and #rewriteIt
location ~ ^(my2|my3) $ {
rewrite ^(.*)$ /ETC.php?cmd=$1 last;
include /etc/nginx/fastcgi.conf; # without SCRIPT_FILENAME
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
fastcgi_pass unix:/run/php/php7.0-fpm.sock;
}
# This RegExp location will proxy to 2018 port
# It is more priority, than "/" and #rewriteIt
location ~ ^(my1|issn) $ {
proxy_pass http://127.0.0.1:2018;
}
# This location handles all php files to php-fpm
location ~ \.php$ {
try_files $uri =404;
include /etc/nginx/fastcgi.conf; # without SCRIPT_FILENAME
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
fastcgi_pass unix:/run/php/php7.0-fpm.sock;
}

Get WordPress installation working with nginx in subdirectory

Basically I have a site, called example.com. Within this site, there is a WordPress-Blog, wich should be accessible under "example.com/blog/". The actual directory where the blog is installed is not "/blog/", but "/blog/de/", as this project has multiple stand-alone-blogs for different languages.
The problem is, that WordPress cannot access to wp-content and wp-include files, because WordPress tries to load css (and other) files via example.com/blog/wp-content/....
So i want to get my Blog running under "example.com/blog", but all WordPress-Files should be loaded from /blog/de/.
This is my nginx-vhost-config for /blog-Location:
location /blog {
index index.php;
try_files $uri $uri/ /de/index.php?$args;
rewrite ^(/wp-content/.*)$ /de/wp-content/$1 last;
rewrite ^/blog/(.*)+$ /blog/de/index.php?$1;
}
rewrite /wp-admin$ $scheme://$host$uri/ permanent;
I am totally new to nginx, so every possible solution is welcome!
Essentially you need to alias the location /blog to the path /blog/de. The complication is the way in which PHP files are handled, particularly when other applications are hosted within the same domain.
First internally rewrite /blog to /blog/de:
location /blog {
rewrite ^/blog(.*)$ /blog/de$1 last;
}
Then implement the /blog/de location with a nested location to handle PHP:
set $wordpress /blog/de/index.php;
location ^~ /blog/de {
# root inherited from server container???
index index.php;
try_files $uri $uri/ $wordpress;
location ~ \.php$ {
try_files $uri $wordpress;
include fastcgi_params;
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
fastcgi_pass ...;
}
}
I make /blog/de a priority prefix location, to avoid a conflict with any other php location. But that would not be necessary if this is the only application within this server block.

Nginx location: 403 error / File not found

I set up my domain on my server using nginx. So far so good my homepage works. But now I wanna add some locations for later test of programming. My plan is to call diffrent projects like mydomain.com/php/myprogramm.php
So I add some folder in /var/www/mydomain.com/php (my side index is in /var/www/mydomain.com/html)
Entering www.mydomain.com/php/ leads to an 403 error and mydomain.com/php/myprogramm.php says File not found...
this is my nginx file:
server {
listen 80 default_server;
#listen [::]:80 default_server ipv6only=on;
# Make site accessible from http://localhost/
server_name mydomain.com www.mydomain.com;
location / {
root /var/www/mydomain.com/html;
index index.html index.htm;
}
location /php/ {
root /var/www/mydomain.com;
}
location /js/ {
root /var/www/mydomain.com;
}
location /node/ {
root /var/www/mydomain.com;
}
# pass the PHP scripts to FastCGI server listening on 127.0.0.1:9000
#
location ~ \.php$ {
fastcgi_split_path_info ^(.+\.php)(/.+)$;
# # NOTE: You should have "cgi.fix_pathinfo = 0;" in php.ini
#
# # With php5-cgi alone:
# fastcgi_pass 127.0.0.1:9000;
# # With php5-fpm:
fastcgi_pass unix:/var/run/php5-fpm.sock;
fastcgi_index index.php;
include fastcgi_params;
}
}
Of course when I set up my domain I also set sudo chown -R www-data:www-data /var/www/mydomain.com/html and sudo chmod 755 /var/www
Some ideas someone? :/
Problems analysis
The first golden rule is:
nginx always serves request from a single location only. (Re-)read http://nginx.org/en/docs/http/request_processing.html.
Based on your configuration:
Requests to (www.)mydomain.com/php/<whatever> for files not ending with .php will be served by location /php/ from /var/www/mydomain.com/php/<whatever>
Requests to (www.)mydomain.com/<whatever>.php will be served by location ~\.php$ from <default root ('html' by default)>/<whatever>.php
The first problem here is that you are not serving .php files from where you think you are. Learn from location documentation how the location block serving a request is chosen.
You will note that the 'File not found' error was not an nginx error, but a message generated by PHP. That helps to know whether the problem comes from (frontend or backend).
Now about that 403: it seems nginx has trouble accessing the location where it is supposed to serve content from. Check /var/www/mydomain.com/php/ (directory + contents) rights.
Proposed pieces of advice
Your configuration looks suboptimal.
If you use the same root in lots of location blocks, why not moving it one level upper so it becomes the default (which yo ucan override in specific locations where needed)?
You can used nested locations, ie to solve you PHP files serving problem. Note that it is always a good idea to enclose regex locations inside prefix locations (What is the difference? Read location documentation). The reason is regex locations are order-sensitive, which is bad for maintenance. Prefix locations are not since only the longest match with a request URI will be chosen.
Here is a propsed updated version of part of your configuration:
root /var/www/mydomain.com;
location / {
root /var/www/mydomain.com/html;
index index.html index.htm;
}
location /php/ {
location ~ \.php$ {
# Useless without use of $fastcgi_script_name and $fastcgi_path_info
# Moreover, requests ending up here always end with .php...
fastcgi_split_path_info ^(.+\.php)(/.+)$;
fastcgi_pass unix:/var/run/php5-fpm.sock;
fastcgi_index index.php;
include fastcgi_params;
# You seem to have copy-pasted this section without understanding it.
# Good understanding of what happens here is mandatory for security.
}
}
I suggest you read the documentation about fastcgi_split_path_info, $fastcgi_script_name and $fastcgi_path_info.
For my testing right now I fixed the issue quite simply.
I forogt to check my php.ini and change the cgi.fix_pathinfo to 0
Also I changed the group for my folders (still had root inside) to www-data.
At the end I updated my configuration: I set root /var/www/mydomain.com; in my server block (server{})
That's all I did.
But I will keep your advice in mind for later issues.
Thanks for your help I appreciate it.

Nginx root directive inside location block is not working as I expect

I'm having a big headache while configuring Nginx to work inside a location block.
I'm developing a web application with Laravel, and it is located at /srv/http/zenith. With Laravel, the index is inside the public folder, so I'm trying to reach it using the following configuration:
location /zenith/ {
root /srv/http/zenith/public;
try_files $uri $uri/ /index.php?$query_string;
location ~ \.php$ {
fastcgi_pass unix:/run/php-fpm/php-fpm.sock;
fastcgi_split_path_info ^(.+\.php)(.*)$;
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
include fastcgi_params;
}
}
But it gets me 404 error everytime. As I read from Nginx documentation, Nginx does not remove the path from the URI, so even inside /zenith/ block, all URIs still start with /zenith/. This way, example.com/zenith points to /srv/http/zenith/public/zenith when I want /srv/http/zenith/public.
How do I fix this error? I expected that Nginx removed this unwanted part automatically, but it seems to be not this way.
You need to understand the difference between a root and alias. A root maps the URI / to the directory mentioned and expects all URI parts after it to match the on disk tree. Alias maps the location of the block it's part of to the directory mentioned and expects all URI parts after this location to match the on disk tree. Since root inside a location block still maps the / URI, the part after / needs to exist on disk for things to work. In the common case you will use root for the document root and alias for location blocks.

Resources