0

I am trying to rewrite to a PHP file in nginx without changing the URL, but php-fpm isn't processing the file and all I get is a 500.

If I remove the rewrite and visit the file directly, it works, so the .php file is not wrong.

server {
    listen 80;
    root /var/www/example.com/public_html;
    server_name example.com www.example.com;
    index index.html index.php;
    add_header Access-Control-Allow-Origin *;

    location ~ ^/InfoCenter/api/.*$ {
        rewrite "/InfoCenter/api/(.*)" /InfoCenter/api/index.php last;
    }

    location / {
        try_files $uri $uri/ =404;
    }

    location ~ \.php$ {
        include snippets/fastcgi-php.conf;
        fastcgi_split_path_info ^(.+\.php)(/.+)$;
        fastcgi_pass unix:/run/php/php7.0-fpm.sock;
        include fastcgi_params;
    }

    location ~/\.htaccess {
        deny all;
    }
}
skiilaa
  • 101
  • 2

2 Answers2

0

Your location for InfoCenter is also catching the place you're rewriting to, as it's matching the regex again. i.e. Your users will be rewritten to /InfoCenter/api/index.php and then just get snagged into the same location. and then never sent to PHP ever.

Try changing the PHP location to be:

location ^~ .*\.php$ {
    ...
}

The change of location to regex prefix will give it precedence over the other location.

Reverend Tim
  • 879
  • 8
  • 14
0

You don't need to use a regular expression in the /InfoCenter/api location. You can use:

location /InfoCenter/api {
    try_files /InfoCenter/api/index.php;
}

This way you will avoid the issue of matching the /InfoCenter path again. It is also slightly faster to do a prefix match than a regular expression match.

Also, try_files is a simpler way to forward all requests with that prefix to the index.php file. It also doesn't actually rewrite the URL, which is part of the problem in your original approach.

Tero Kilkanen
  • 36,796
  • 3
  • 41
  • 63
  • The problem is that I am accessing /InfoCenter/api/weather/, and index.php depends on the URL. – skiilaa Aug 30 '17 at 17:16
  • Your `rewrite` on the original question forwarded all requests to `/InfoCenter/api/index.php`. Please clarify your exact use case in your question. – Tero Kilkanen Aug 30 '17 at 17:28