John Davidson

PHP files not automatically loaded in nginx

0 comments
Message:


When I try to access my site I have to manually type index.php at the end of the url. I'm trying to have automatically load my index.php file when accessing the site. My nginx config file looks like this.


server {
listen 80;


root /var/www/html/myapp/public;

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

server_name _;

add_header X-Frame-Options "SAMEORIGIN";
add_header X-XSS-Protection "1; mode=block";
add_header X-Content-Type-Options "nosniff";

charset utf-8;

location / {
index index.html index.htm index.php;
# try_files $uri $uri/ /index.php?$query_string;
try_files $uri $uri/ = 404;
}

location = /favicon.ico { access_log off; log_not_found off; }
location = /robots.txt { access_log off; log_not_found off; }

error_page 404 /index.php;


location ~ \.php$ {
fastcgi_pass unix:/var/run/php/php8.0-fpm.sock;
fastcgi_index index.php;
fastcgi_param SCRIPT_FILENAME $realpath_root$fastcgi_script_name;
include fastcgi_params;
}

location ~ /\.(?!well-known).* {
deny all;
}
}


My Answer:
To automatically load the index.php file when accessing your site, you need to configure nginx to recognize PHP files and pass them to the PHP processor. You can do this by adding a location block in your nginx configuration file. Here's an example of how you can modify your configuration:


server {
listen 80;
root /var/www/html/myapp/public;

index index.php index.html index.htm;

location / {
try_files $uri $uri/ /index.php?$query_string;
}

location ~ \.php$ {
include snippets/fastcgi-php.conf;
fastcgi_pass unix:/var/run/php/php7.4-fpm.sock;
}
}


In this configuration, the `location /` block is used to try serving the requested URI directly, and if it doesn't exist, it will pass the request to index.php. The `location ~ \.php$` block is used to handle PHP files and pass them to the PHP processor.

After making these changes, don't forget to reload nginx for the changes to take effect:


sudo systemctl reload nginx


Now, when you access your site, the index.php file should be automatically loaded.

Rate this post

4 of 5 based on 9022 votes

Comments




© 2024 Hayatsk.info - Personal Blogs Platform. All Rights Reserved.
Create blog  |  Privacy Policy  |  Terms & Conditions  |  Contact Us