hanshenrik
hanshenrik

Reputation: 21463

Nginx send all requests from subdirectory to php-fpm?

how can i redirect all requests going to /api/v1/*ANYTHING* to /api/v1/router.php ? my current nginx config is:

server {
    listen 80 default_server;
    listen [::]:80 default_server;

    # SSL configuration
    #
    # listen 443 ssl default_server;
    # listen [::]:443 ssl default_server;
    #
    # Self signed certs generated by the ssl-cert package
    # Don't use them in a production server!
    #
    # include snippets/snakeoil.conf;

    root /srv/http/default/www;
    autoindex on;

    # Add index.php to the list if you are using PHP
    index index.html index.htm index.php;

    server_name _;

    location / {
        # First attempt to serve request as file, then
        # as directory, then fall back to displaying a 404.
        try_files $uri $uri/ =404;
    }
    # pass PHP scripts to FastCGI server
    #
    location ~ \.php$ {
        include snippets/fastcgi-php.conf;
        # With php-fpm (or other unix sockets):
        fastcgi_pass unix:/var/run/php/php7.2-fpm.sock;
        # With php-cgi (or other tcp sockets):
    #   fastcgi_pass 127.0.0.1:9000;
    }
    # deny access to .htaccess files, if Apache's document root
    # concurs with nginx's one
    #
    #location ~ /\.ht {
    #   deny all;
    #}
}

and things i have tried:

location /api/v1 {
    try_files FIXME_DO_NOT_MAKE_FILE_WITH_THIS_NAME /api/v1/router.php$is_args$args;
}

have also tried:

location /api/v1 {
    rewrite ^/api/v1/(.*)$ /api/v1/router.php last;
}

.. which seems to suffer from exactly the same issue as above, as long as the url does not end in .php it works, otherwise i get 404's... i guess it has something to do with the location ~ \.php$ block taking precedence, but it doesn't matter if i put my rewrite rule above or below the .php$ block... so now i'm kindof stumped

(also not sure if this question belongs on SO or serverfault or superuser, but given that similar questions like Nginx redirect all requests from subdirectory to another subdirectory root exists on SO, i decided on trying here)

Upvotes: 0

Views: 1339

Answers (1)

Danila Vershinin
Danila Vershinin

Reputation: 9845

The most straightforward solution would be to define a "regex" location, and directly specify script name that will be the one processing all requests, like so:

location ~ ^/api/v1/ {
    include snippets/fastcgi-php.conf;
    fastcgi_pass unix:/var/run/php/php7.2-fpm.sock;
    fastcgi_param SCRIPT_FILENAME $document_root/api/v1/router.php;
}

Make sure to put this above the location ~ \.php$ { because NGINX checks regex locations in order of appearance in configuration files.

Upvotes: 1

Related Questions