配置Nginx使Laravel项目正常运行需将根目录设为public,使用try_files实现URL重写,处理PHP请求并禁止访问敏感文件,推荐配置HTTPS并强制跳转,最后测试配置并重启Nginx服务。

在部署 Laravel 项目时,为了让应用正常运行并支持“隐藏 index.php”和友好的 URL 路由,必须正确配置 Nginx 的 URL 重写规则。Laravel 使用前端控制器(public/index.php)来处理所有 HTTP 请求,因此需要将所有请求指向该文件,除非请求的是实际存在的静态资源。
确保你的 Nginx 配置文件(通常位于 /etc/nginx/sites-available/your-site)正确设置站点根目录为 Laravel 的 public 目录,并启用 URL 重写:
server { listen 80; server_name your-domain.com; root /var/www/your-laravel-project/public;
# 指定默认索引文件
index index.php index.html index.htm;
# 处理所有请求,优先查找真实文件,否则重写到 index.php
location / {
try_files $uri $uri/ /index.php?$query_string;
}
# PHP 处理
location ~ \.php$ {
include snippets/fastcgi-php.conf;
fastcgi_pass unix:/var/run/php/php8.1-fpm.sock; # 根据你的PHP版本调整
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
include fastcgi_params;
}
# 隐藏敏感文件
location ~ /\.(env|git) {
deny all;
}}
try_files $uri $uri/ /index.php?$query_string; 是实现 URL 重写的核心指令:
这样访问 your-domain.com/users/1 会被正确路由到 Laravel 而不是返回 404。
若使用 HTTPS,需添加 SSL 配置,并强制跳转:
server { listen 443 ssl http2; server_name your-domain.com; root /var/www/your-laravel-project/public; ssl_certificate /path/to/fullchain.pem; ssl_certificate_key /path/to/privkey.pem;location / {
try_files $uri $uri/ /index.php?$query_string;
}
location ~ \.php$ {
include snippets/fastcgi-php.conf;
fastcgi_pass unix:/var/run/php/php8.1-fpm.sock;
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
include fastcgi_params;
}}
server { listen 80; server_name your-domain.com; return 301 https://www.php.cn/link/21964698b7df1cefa6befc89697f5293; }
完成配置后,执行以下命令验证并生效:
sudo nginx -t若输出 “syntax is ok”,则表示配置无误,接着重启服务:
sudo systemctl reload nginx确保 storage 和 bootstrap/cache 目录有正确的读写权限,避免 Laravel 报错。
基本上就这些。只要 Nginx 指向了 public 目录,并正确使用 try_files 指令,Laravel 的路由就能正常工作。
以上就是laravel项目如何配置Nginx实现URL重写_Laravel项目Nginx URL重写配置教程的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号