I cannot figure out how should I setup my index.php file with Nginx rewrite rules that it will work like example below.

If I visit the url it gives me 404 error not found instad echo 'hello'.



/sub-directory/ from given URL actually is not real directory inside /directory/. If I visit the URL, i got 404 error - which is real ok, but /sub-directory/ is friendly URL (without query ?argument=value).

/sub-directory/ is not fixed value (in this example below it is), it can be /sub-directory-new/ - depends.

So, for any value within /value/ after /directory/ in URL, how could I not get 404 error if I visit that kind of URL?

Index.php in /directory/:

$actual_link = "http://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
$wanted = "sub-directory";

$tokens = explode('/', $actual_link);
$result =  $tokens[sizeof($tokens)-2]; // result is "sub-directory"
if($wanted == $result) {
    echo "hello";


location /directory {
    try_files $uri $uri/ /directory/$uri;
    error_page 404 =200 /directory

Should I add some arguments for the rule, like: location /directory$1? If so, which one and how to get it working?

Anyone got some ideas?

Thanks for sharing and info!


The usual way of doing friendly URLs in nginx is like this:

location /directory {
    try_files $uri $uri/ @rewrites;

location @rewrites {
    rewrite ^ /directory/index.php;

This configuration assumes that your root directive points to the directory where /directory is located.

So, here nginx will try first if the file or directory exists in the real filesystem. If the file does not exist, then it forwards the request to your PHP file. Naturally you need to have your PHP processing block correctly configured in nginx.

| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.