如何在nginx中设置虚拟主机


how to set up virtual host in nginx?

我使用以下配置设置,但它在执行时下载索引源文件。但是,如果将index.html而不是index.php 放进去,它将显示index.html的输出

总的来说,它似乎并没有读取php文件。

 server {
 server_name test.com;
 root /var/www/test;
 index index.html index.php;
 # serve static files directly
 location ~* '.(jpg|jpeg|gif|css|png|js|ico|html)$ {
 access_log off;
 expires max;
}
location / {
    # Check if a file or directory index file exists, else route it to index.php.
    try_files $uri $uri/ /index.php;
}
location ~ /'.ht {
deny  all;
}
}

您必须设置PHP-FPM或fastcgi,否则您将获得纯文件:

fastcgi_pass 127.0.0.1:9000;
fastcgi_param SCRIPT_FILENAME /var/www/test/index.php;
fastcgi_param PATH_INFO $fastcgi_script_name;
fastcgi_pass_header Host;
fastcgi_pass_header X-Real-IP;
include /etc/nginx/fastcgi_params;

PHP-FPM应该在端口9000 中运行

这是我的基本虚拟主机文件

server {
    server_name example.com www.example.com;
    root /path/to/root;
    location / {
        try_files $uri $uri/ /index.php$request_uri;
    }
    location ~* '.php$ {
        include fastcgi_params;
        fastcgi_pass unix://var/run/php5-fpm.sock # if you use sock files
        fastcgi_pass http://127.0.0.1:9000; # if you use port 9000
    }
}

根据您的网站使用的内容,您需要对其中一行fastcgi_pass进行评论。当然,您需要自定义try_files行以匹配php获取路由的方式,例如,如果您使用QUERY_STRING,您可能会执行类似的操作

try_files $uri $uri/ index.php?$request_uri; # mind the extra `?`

如果您收到一个坏网关[502]错误

,请仔细检查/var/run目录中的sock文件的路径