rabudde
rabudde

Reputation: 7722

Nginx location behave with and without location regex

To include my small project (not based on one of the known frameworks) into existing website, I've added the following config to Nginx

server {
    listen 80 default_server;
    server_name localhost;
    access_log /var/log/nginx/dev.access.log;
    error_log /var/log/nginx/dev.error.log;
    root /var/www;
    index index.php;

    [...]

    location /www.my-project.com {
        alias /var/www/www.my-project.com/web;
        index index.php;
        if (-f $request_filename) { break; }
        rewrite ^(.*)$ /www.my-project.com/index.php last;
        location ~ /[^/]+/index\.php$ {
            include fastcgi_params;
            fastcgi_pass unix:/var/run/fcgi.sock;
            fastcgi_param  SCRIPT_FILENAME  $document_root/index.php;
        }
    }

All works fine (except that I wish to prevent to list subdir name in location directive), so I can call http://localhost/www.my-project.com. But when calling http://localhost/www.my-project.com.blabla the location directive from above is called and my internal error page is served. So I tried to change location directive to

    location ~ ^/www\.my-project\.com(/|$) {

But that causes any existing file (CSS, JS...) to be rewritten to index.php, which then returns an 404 itself. Why does a change of location causes this horrible behaviour, I can see no logical difference between location /www.my-project.com and location ~ ^/www\.my-project\.com(/|$).

Upvotes: 1

Views: 1785

Answers (1)

Mohammad AbuShady
Mohammad AbuShady

Reputation: 42799

I'd suggest excluding the assets from the rewrite, you can do that by adding a new location, something like this

location /(css|js|images) {
    root /var/www/www.my-project.com/web;
    try_files $uri =404;
}

And for the location issue, you can match exact locations using =

location = /www.my-project.com {

Upvotes: 2

Related Questions