0

I currently have an nginx config that enables requests for files such as "/contact.php" to be made with just "/contact". And I found a solution for redirecting any .php request to its friendly counterpart, however, I thought there may be a more elegant solution.

Is it possible to 403 or 404 requests made to a URI such as "/articles/index.php" or "/articles/index" (note that friendly URI rewrite is enabled) and only accept requests via "/articles/" which would still load the "/articles/index.php" file?

Basically, I want any "/index" or "/index.php" in any dir, or .php request to 403 or 404, and only accept the friendly extensionless request or directory root / to load index.php (without it being requested in the URI).

Is this possible? I tried something like this in my config to deny .php requests, but since there is technically a rewrite, it will just deny all requests. It is not currently in there as it did not work.

Current config:

location / {
try_files $uri $uri/ @extensionless-php;
index index.php;
}

location @extensionless-php {
rewrite ^(.*)$ $1.php last;
}

location ~ /includes/(.+)\.php$ {
deny all;
}

location ~ \.php {
try_files $uri =404;
fastcgi_pass backend;
fastcgi_index index.php;
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
include fastcgi_params;
}
Dogbert
  • 77
  • 1
  • 8
  • are there any issues with my answer, or did it fully solve your question? if the latter, i'd appreciate if you can accept and upvote. thanks! – cnst Jul 03 '16 at 01:59

1 Answers1

0

This appears to be somewhat of a duplicate of your later question, but, in case you still want this addressed, the following code should do what you want, without actually denying all the requests.

if ($request_uri ~ "^[^?]*?(/index(?:\.php)?|\.php)(?:\?.*)?$") {   return  403;    }

Some debugging with pcre (which is the library that nginx uses).

$ pcretest
PCRE version 8.30 2012-02-04

  re> #^[^?]*?(/index(?:\.php)?|\.php)(?:\?.*)?$#
data> /test
No match
data> /test.php
 0: /test.php
 1: .php
data> /index.php
 0: /index.php
 1: /index.php
data> /iindex.php
 0: /iindex.php
 1: .php
data>
Community
  • 1
  • 1
cnst
  • 25,870
  • 6
  • 90
  • 122