【问题标题】:how to set up virtual host in nginx?如何在 nginx 中设置虚拟主机?
【发布时间】:2013-11-26 21:41:01
【问题描述】:

我正在使用以下配置设置,但它正在下载执行时的索引源文件。但是如果放置 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;
}
}

【问题讨论】:

    标签: nginx web fastcgi php


    【解决方案1】:

    你必须设置 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 端口运行

    【讨论】:

    • 在设置 fastcgi 之前是否需要安装一些东西?我已经安装了 nginx 就够了吗?
    • 您需要 php-fpm,作为服务运行。这将执行你的 php 文件。
    • 非常感谢。我现在可以执行 php 文件。但它没有采用任何其他网址。我的意思是在 Apache 中我们需要 mod_rewrite,同样我们需要在这里做什么?例如https://test.com/auth/register 无法识别
    • 然后你必须把 /var/www/test/index.php 改成 /var/www/test/$uri
    【解决方案2】:

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

    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 文件的路径

    【讨论】:

      猜你喜欢
      • 2023-03-15
      • 2012-01-02
      • 2016-01-03
      • 1970-01-01
      • 2014-11-12
      • 2011-01-23
      • 2021-08-30
      • 2016-11-09
      • 1970-01-01
      相关资源
      最近更新 更多