《yii nginx.conf 配置》
解决方案
在使用Yii框架时,正确的Nginx配置是确保应用程序正常运行的关键。通过调整nginx.conf
文件,我们可以优化性能、提高安全性并确保URL路由正确解析。提供多种配置方案,以满足不同场景下的需求。
默认配置
这是最基础的配置方式,适用于大多数简单的Yii项目:
nginx
server {
listen 80;
server_name yourdomain.com;</p>
<pre><code># 设置根目录为web
root /path/to/yii/web;
index index.php;
location / {
try_files $uri $uri/ /index.php?$args;
}
location ~ .php$ {
fastcgi_pass 127.0.0.1:9000;
fastcgi_index index.php;
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
include fastcgi_params;
}
}
启用pretty URL
当您想使用干净美观的URL时,需要做如下修改:
nginx
location / {
try_files $uri $uri/ /index.php?r=$uri&$args;
}</p>
<p>location ~ ^/assets/.*.php$ {
deny all;
}</p>
<p>location ~ ^/(protected|framework|themes/w+/views) {
deny all;
}
注意:此配置会将所有请求重定向到index.php
,并通过参数r
传递原始路径。
增强安全性的配置
为了提高安全性,可以添加以下规则:
nginx</p>
<h1>禁止访问敏感文件</h1>
<p>location ~* /(yii|runtime|tests)/ {
deny all;
}</p>
<h1>防止PHP文件直接执行</h1>
<p>location ~* ^.+.(engine|inc|info|install|make|module|profile|test|po|sh|.<em>sql|theme|tpl(.php)?|xtmpl)$|^(..</em>|Entries.*|Repository|Root|Tag|Template)$ {
return 404;
}</p>
<h1>禁用目录浏览</h1>
<p>autoindex off;
缓存优化配置
对于静态资源,可以设置缓存策略来提升性能:
nginx
location ~* .(js|css|png|jpg|jpeg|gif|ico|woff|ttf|svg|eot)$ {
expires max;
add_header Cache-Control "public";
}</p>
<h1>对于HTML页面设置较短的缓存时间</h1>
<p>location ~* .html$ {
expires 30m;
add_header Cache-Control "private, no-transform";
}
HTTPS配置(可选)
如果您的网站支持SSL/TLS,建议使用以下配置:
nginx
server {
listen 443 ssl;
server_name yourdomain.com;</p>
<pre><code>ssl_certificate /etc/nginx/ssl/cert.pem;
ssl_certificate_key /etc/nginx/ssl/key.pem;
# 其他配置与上面相同...
}
强制HTTP跳转到HTTPS
server {
listen 80;
servername yourdomain.com;
return 301 https://$host$requesturi;
}
根据您的具体需求选择合适的配置方案,并进行适当的调整。记得每次修改后都要测试配置是否正确:sudo nginx -t
,然后再重新加载Nginx服务:sudo service nginx reload
。