yii nginx.conf 配置

2025-03-11 0 24

《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$request
uri;
}

根据您的具体需求选择合适的配置方案,并进行适当的调整。记得每次修改后都要测试配置是否正确:sudo nginx -t,然后再重新加载Nginx服务:sudo service nginx reload

Image

1. 本站所有资源来源于用户上传和网络,因此不包含技术服务请大家谅解!如有侵权请邮件联系客服!cheeksyu@vip.qq.com
2. 本站不保证所提供下载的资源的准确性、安全性和完整性,资源仅供下载学习之用!如有链接无法下载、失效或广告,请联系客服处理!
3. 您必须在下载后的24个小时之内,从您的电脑中彻底删除上述内容资源!如用于商业或者非法用途,与本站无关,一切后果请用户自负!
4. 如果您也有好的资源或教程,您可以投稿发布,成功分享后有积分奖励和额外收入!
5.严禁将资源用于任何违法犯罪行为,不得违反国家法律,否则责任自负,一切法律责任与本站无关

源码下载