0

I'm setting up an Nginx + PHP web server on AWS Linux 2. It is a fresh install with nginx and PHP7.4 installed. Below is the virtual host config file in nginx.

I need to redirect all the traffic to index.php because it is a Single Page App.

When I go to www.xxx.com/index.php, the PHP page renders fine (so PHP is definitely running).

When I go to www.xxx.com/login/, the browser prompts for download of the index.php file instead of executing it.

Can anyone please help? (I've tried to clear my browser cache).

/etc/nginx/conf.d/myapp.conf

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

    root /var/www/vhosts/app.userback.io/frontend/;
    index index.php index.html index.htm;

    server_name www.myapp.com;

    location / {
        try_files $uri $uri/ /index.php =404;
    }

    location ~ \.php$ {
        try_files $uri =404;

        fastcgi_split_path_info ^(.+\.(?:php|phar))(/.*)$;
        fastcgi_intercept_errors on;
        fastcgi_index  index.php;
        include        fastcgi_params;
        fastcgi_param  SCRIPT_FILENAME  $document_root$fastcgi_script_name;
        fastcgi_param  PATH_INFO $fastcgi_path_info;
        fastcgi_pass   php-fpm;
    }
}
Lee Le
  • 337
  • 1
  • 4
  • 10

2 Answers2

0

Can you try:

location ~ \.php$ {
    try_files $uri /404.html;
    fastcgi_pass unix:/var/run/php-fpm/php-fpm.sock;// change it if not valid
    fastcgi_index index.php;
    fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
    include fastcgi_params;
} 
laguf1.mobi
  • 171
  • 6
  • I've tried yours. It still prompts for downloading of the PHP file instead of executing it. When I go to the PHP file directly, it executes it fine. The download only occurs when the try_files tries to serve the traffic with index.php. – Lee Le Nov 16 '20 at 03:52
  • you try: try_files $uri $uri/ /index.php?$args; – laguf1.mobi Nov 16 '20 at 03:56
  • Thx, I tried. It didn't work. It no longer prompts for download because it doesn't redirect to index.php anymore. :( – Lee Le Nov 16 '20 at 04:08
  • what the return code of nginx ? 404, 403 .. 200 or 50x ? – laguf1.mobi Nov 16 '20 at 04:16
  • It's a good 200 code. But the content-type is application/octet-stream. It managed to "redirect" or server the traffic made to /login/ with index.php because /login/ isn't a file that exists. But it should execute index.php on the server instead of retuning it as a file for download. Hope that makes sense. BTW, PHP is definitely installed and running because we I go to index.php directly, it works fine. – Lee Le Nov 16 '20 at 04:23
0

I've found the answer here: NGINX try_files does not pass to PHP.

It turns out it is the order of the location plus removing the 404 to make the redirect internal.

Lee Le
  • 337
  • 1
  • 4
  • 10