Nginx设置默认首页,index.html配置
前言
访问网站根目录,Nginx 不知道默认打开哪个文件,就返回 403 或者 404。这是因为没配置默认首页。本文讲一下 Nginx 怎么设置默认首页。
什么是默认首页
用户访问 www.example.com/,Nginx 自动找目录下的 index.html 打开,不用手动输入文件名。
配置方法
用 index 指令设置:
server {
listen 80;
server_name www.example.com;
root /var/www/html;
index index.html;
}
多个默认首页
Nginx 会按顺序找,找到第一个存在的就用:
index index.html index.htm index.php;
意思是:先找 index.html,没有就找 index.htm,再没有就找 index.php。
完整站点配置
server {
listen 80;
server_name www.example.com;
root /var/www/html;
index index.php index.html index.htm;
location / {
try_files $uri $uri/ =404;
}
location ~ \.php$ {
fastcgi_pass unix:/run/php-fpm/www.sock;
fastcgi_index index.php;
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
include fastcgi_params;
}
}
自定义默认首页
不想用 index.html,想用别的文件名?
index default.html;
这样访问根目录就打开 default.html。
常见坑
坑1:访问根目录 403 Forbidden
配置了 root,也放了 index.html,但访问还是 403。
原因1: 文件名写错了,比如是 Index.html(大写 I)。
解决: Linux 区分大小写,文件名必须和 index 配置一致。
原因2: 文件权限不对。
解决: 确保文件权限是 644,目录是 755。
坑2:默认首页不生效
改了 index 配置,但还是打开旧的首页。
原因: 没重载 Nginx。
解决:
nginx -s reload
坑3:PHP 首页不解析
默认首页设成 index.php,但访问直接下载 PHP 文件。
原因: PHP 解析配置没写对。
解决: 确保有 PHP 的 location 配置:
location ~ \.php$ {
fastcgi_pass unix:/run/php-fpm/www.sock;
fastcgi_index index.php;
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
include fastcgi_params;
}
坑4:静态首页和 PHP 首页顺序
index 里先写 index.html 还是 index.php?
建议: 把常用的放前面。如果主要是 PHP 程序,就把 index.php 放前面。
总结
一行配置搞定:
index index.php index.html index.htm;
记住: index 后面跟多个文件名,Nginx 按顺序找,找到第一个存在的就用。
遇到问题加QQ23979811 协助处理