【问题标题】:Configure nginx to run subsites配置 nginx 运行子站点
【发布时间】:2016-09-28 14:51:41
【问题描述】:

我能够按照教程设置 nginx 服务器块。当我尝试通过各自的域名访问这些站点时,我被定向到同一个站点。 我一直在尝试在 Windows 的 localhost 下创建多个 /site1 的子站点。

nginx.conf

#user  nobody;
# worker_processes  1;
worker_processes  auto;

# error_log  logs/error.log;
# error_log  logs/error.log  notice;
# error_log  logs/error.log  info;

#pid        logs/nginx.pid;

events {
    worker_connections  1024;
}

http {
    include       mime.types;
    default_type  application/octet-stream;

    #log_format  main  '$remote_addr - $remote_user [$time_local] "$request" '
    #                  '$status $body_bytes_sent "$http_referer" '
    #                  '"$http_user_agent" "$http_x_forwarded_for"';

    #access_log  logs/access.log  main;

    sendfile        on;
    #tcp_nopush     on;

    #keepalive_timeout  0;
    keepalive_timeout  65;

    #gzip  on;

    server {
        listen       80;
        server_name  localhost;

        #charset koi8-r;

        #access_log  logs/host.access.log  main;

        location / {
            root   H:\www\html;
            index  index.html index.htm;
        }

        #error_page  404              /404.html;

        # redirect server error pages to the static page /50x.html
        #
        error_page   500 502 503 504  /50x.html;
        location = /50x.html {
            root   H:\www\html;
        }

        # this is the default server
        location = /site1 {
          return 301 /site1/;
        }
        location ^~ /site1/ {
            root H:\www\html\drupal-8.1.10;
            index  index.php;

        }
        location ~ /site1/\.php$  {
            fastcgi_split_path_info ^(.+\.php)(/.+)$;
            fastcgi_pass    127.0.0.1:9123;
            fastcgi_index index.php;
            include fastcgi_params;
        }
    }
}

www 目录:

H:\www\html>tree /f
Folder PATH listing for volume 975
Volume serial number is 0000-043C
H:.
│   50x.html
│   index.html
│   drupal.tar.gz
│
└───drupal-8.1.10
        index.php

潜在的 URL 应该是:

本地主机
本地主机/站点1

谢谢

【问题讨论】:

    标签: php nginx


    【解决方案1】:

    在 Windows 中使用:

    nginx 同一驱动器上的路径,例如:

    H:/nginx

    pid 完整的绝对路径,例如:

    pid    H:/nginx/logs/nginx.pid;
    

    错误日志启用例如(取消注释):

    error_log  logs/error.log;
    error_log  logs/error.log  notice;
    error_log  logs/error.log  info;
    

    设置|启用输出日志格式

    log_format  main  '$remote_addr - $remote_user [$time_local] "$request" '
                      '$status $body_bytes_sent "$http_referer" '
                      '"$http_user_agent" "$http_x_forwarded_for"';
    

    正确的根进入服务器块是(双“”):

    server{
      location /{
         root  "H:/nginx/www/html";
      }
    }
    

    正确的 php fastCGI 参数 例如:

    server{
        location ~ /site1/\.php$  {
            root                         www/html/site1
            fastcgi_pass                 127.0.0.1:9000;
            fastcgi_index                index.php;
            fastcgi_param                SCRIPT_FILENAME C:/nginx/www/html/site1$fastcgi_script_name;
            fastcgi_split_path_info      ^(.+\.php)(.*)$;
            fastcgi_param PATH_INFO      $fastcgi_path_info;
            fastcgi_param QUERY_STRING   $query_string;
            fastcgi_param REQUEST_METHOD $request_method;
            fastcgi_param CONTENT_TYPE   $content_type;
            fastcgi_param CONTENT_LENGTH $content_length;
    
            include                      fastcgi_params;
        }
    }
    

    嗯,我想就是这样。 所有的根设置都必须用双引号括起来,正常的竖线 (/) 不要忘记查看错误日志……它说了很多 :)

    我的示例配置:

    init.bat (to start|close service)[不能为你服务]

    @ECHO OFF
                                 TITLE LOCALHOST SERVICE
    
                                   REM GO TO NGINX DIR
                                      CD C:/nginx
    
    TASKLIST /FI "IMAGENAME eq nginx.exe" | FIND  /I "nginx.exe" > NUL && (GOTO STOP) || (GOTO START)
    
    :START
    ECHO.
    ECHO ---------------------------- STARTING NGINX SERVER ----------------------------
    ECHO.
                                 REM START NGINX SERVICE
                                   START/MIN nginx.exe                             
    ECHO.
    ECHO ----------------------------- STARTER PHP SERVICE -----------------------------
    ECHO.
                             REM START PHP SERVICE (FOR NGINX)
                 php/php-cgi.exe -b 127.0.0.1:9000 -c C:/nginx/php/php.ini
    
                  REM GO TO "END" BLOCK FOR DON'T EXECUTE "STOP" BLOCK ¬¬
                                        GOTO END
    
    :STOP
    
                               REM QUIT|STOP NGINX SERVICE
                         REM OLD-COMMAND: START nginx.exe -s quit
                              TASKKILL /F /IM nginx.exe > NUL
    
                                   REM STOP PHP SERVICE
                             TASKKILL /F /IM php-cgi.exe > NUL
    
                                        GOTO END
    
    :END
    

    好的,init.bat 文件让您只需双击简单即可启动或停止 nginx 和 php。

    您可以在其中添加某人图标并将其放置在这样的工作区域中。

    假设 php 在 nginx 子目录中运行,结构如下:

     // System hard drive (in my case)
     ---C:
        |        // nginx path
        |--------nginx
                   |
                   |---nginx.exe  //executable
                   |
                   |---conf // configurations path
                   |
                   |---logs // logs path
                   |
                   |---pid // path to pid your proccess
                   |
                   |---html //  path to your server (or blocks)
                   |
                   |---mime.types // archive list mime types
                   |
                   |---init.bat // optinal
    

    一个好的做法是使用服务器块,即使它们不使用子域。

    为此,在“C:/nginx/conf”中创建一个名为“sites-enabled”的文件夹,并为此类“nginx”制作一个“备份”您的 nginx 配置文件“C:/nginx/conf/nginx.conf” .conf.bk”。

    新的配置文件如下所示:

    nginx.conf(修改)

     # Configuration File - Nginx Server Configs
     # http://nginx.org/en/docs/dirindex.html     
    
     # Run as a unique, less privileged user for security reasons.
     # user www www;     
    
     # Sets the worker threads to the number of CPU cores available in the system for best performance.
     # Should be > the number of CPU cores.
     # Maximum number of connections = worker_processes * worker_connections
     worker_processes auto;     
    
     # Maximum number of open files per worker process.
     # Should be > worker_connections.
     worker_rlimit_nofile 8192;     
    
     events {
       # If you need more connections than this, you start optimizing your OS.
       # That's probably the point at which you hire people who are smarter than you as this is *a lot* of requests.
       # Should be < worker_rlimit_nofile.
       worker_connections 8000;
     }     
    
     # Log errors and warnings to this file
     # This is only used when you don't override it on a server{} level
     error_log  logs/error.log warn;     
    
     # The file storing the process ID of the main process
     pid        C:/nginx/pids/nginx.pid;     
     
    
     http {     
    
       # Hide nginx version information.
       server_tokens off;     
    
       # Specify MIME types for files.
       include       mime.types;
       default_type  application/octet-stream;     
    
       # Update charset_types to match updated mime.types.
       # text/html is always included by charset module.
       charset_types text/css text/plain text/vnd.wap.wml application/javascript application/json application/rss+xml application/xml;     
    
       # Include $http_x_forwarded_for within default format used in log files
       log_format  main  '$remote_addr - $remote_user [$time_local] "$request" '
                         '$status $body_bytes_sent "$http_referer" '
                         '"$http_user_agent" "$http_x_forwarded_for"';     
    
       # Log access to this file
       # This is only used when you don't override it on a server{} level
       access_log logs/access.log main;     
    
       # How long to allow each connection to stay idle.
       # Longer values are better for each individual client, particularly for SSL,
       # but means that worker connections are tied up longer.
       keepalive_timeout 20s;     
    
       # Speed up file transfers by using sendfile() to copy directly
       # between descriptors rather than using read()/write().
       # For performance reasons, on FreeBSD systems w/ ZFS
       # this option should be disabled as ZFS's ARC caches
       # frequently used files in RAM by default.
       sendfile        on;     
    
       # Don't send out partial frames; this increases throughput
       # since TCP frames are filled up before being sent out.
       tcp_nopush      on;     
    
       # Enable gzip compression.
       gzip on;     
    
       # Compression level (1-9).
       # 5 is a perfect compromise between size and CPU usage, offering about
       # 75% reduction for most ASCII files (almost identical to level 9).
       gzip_comp_level    5;     
    
       # Don't compress anything that's already small and unlikely to shrink much
       # if at all (the default is 20 bytes, which is bad as that usually leads to
       # larger files after gzipping).
       gzip_min_length    256;     
    
       # Compress data even for clients that are connecting to us via proxies,
       # identified by the "Via" header (required for CloudFront).
       gzip_proxied       any;     
    
       # Tell proxies to cache both the gzipped and regular version of a resource
       # whenever the client's Accept-Encoding capabilities header varies;
       # Avoids the issue where a non-gzip capable client (which is extremely rare
       # today) would display gibberish if their proxy gave them the gzipped version.
       gzip_vary          on;     
    
       # Compress all output labeled with one of the following MIME-types.
       gzip_types
         application/atom+xml
         application/javascript
         application/json
         application/ld+json
         application/manifest+json
         application/rss+xml
         application/vnd.geo+json
         application/vnd.ms-fontobject
         application/x-font-ttf
         application/x-web-app-manifest+json
         application/xhtml+xml
         application/xml
         font/opentype
         image/bmp
         image/svg+xml
         image/x-icon
         text/cache-manifest
         text/css
         text/plain
         text/vcard
         text/vnd.rim.location.xloc
         text/vtt
         text/x-component
         text/x-cross-domain-policy;
       # text/html is always compressed by gzip module     
    
       # This should be turned on if you are going to have pre-compressed copies (.gz) of
       # static files available. If not it should be left off as it will cause extra I/O
       # for the check. It is best if you enable this in a location{} block for
       # a specific directory, or on an individual server{} level.
       # gzip_static on;     
    
       # Include files in the sites-enabled folder. server{} configuration files should be
       # placed in the sites-available folder, and then the configuration should be enabled
       # by creating a symlink to it in the sites-enabled folder.
       # See doc/sites-enabled.md for more info.     
    
       include C:/nginx/conf/sites-enabled/*.conf;     
    
     }
    

    请注意,本示例的末尾我们“包括”了“启用站点”文件夹的所有文件“.conf”。

    如果您不使用服务器块,您可以简单地创建一个包含服务器设置的文件“default.conf”。

    类似这样的:

    default.conf(示例)

      server {     
    
         listen                     80;     
    
         keepalive_timeout          300s;
    
         # define path to this project
         root                       "C:/nginx/html/your_path_here";
         # Specify a charset
         charset                    utf-8;
         # define your server name
         server_name                localhost;
         index                      index.php index.html;
         autoindex                  off; 
    
         # pass the PHP scripts to FastCGI server listening on 127.0.0.1:9000 ------------------------------
         #
         location ~ \.php$ {
             # root for PHP FASTCGI MAPING
             root                         html/your_path_here;
             fastcgi_pass                 127.0.0.1:9000;
             fastcgi_index                index.php;
             fastcgi_param                SCRIPT_FILENAME C:/nginx/html/your_path_here$fastcgi_script_name;
             fastcgi_split_path_info      ^(.+\.php)(.*)$;
             fastcgi_param PATH_INFO      $fastcgi_path_info;
             fastcgi_param QUERY_STRING   $query_string;
             fastcgi_param REQUEST_METHOD $request_method;
             fastcgi_param CONTENT_TYPE   $content_type;
             fastcgi_param CONTENT_LENGTH $content_length;    
    
             include        fastcgi_params;
         }
    
         # Prevent clients from accessing hidden files (starting with a dot) -------------------
         # This is particularly important if you store .htpasswd files in the site hierarchy
         # Access to `/.well-known/` is allowed.
         # https://www.mnot.net/blog/2010/04/07/well-known
         # https://tools.ietf.org/html/rfc5785
         location ~* /\.(?!well-known\/) {
           deny all;
         }     
    
         # Prevent clients from accessing to backup/config/source files ------------------------
         location ~* (?:\.(?:bak|conf|dist|fla|in[ci]|log|psd|sh|sql|sw[op])|~)$ {
           deny all;
         }     
    
         # Expire rules for static content -----------------------------------------------------     
    
         # No default expire rule. This config mirrors that of apache as outlined in the
         # html5-boilerplate .htaccess file. However, nginx applies rules by location,
         # the apache rules are defined by type. A consequence of this difference is that
         # if you use no file extension in the url and serve html, with apache you get an
         # expire time of 0s, with nginx you'd get an expire header of one month in the
         # future (if the default expire rule is 1 month). Therefore, do not use a
         # default expire rule with nginx unless your site is completely static         
    
         # cache.appcache, your document html and data -----------------------------------------
         location ~* \.(?:manifest|appcache|html?|xml|json)$ {
           expires -1;
           access_log logs/static.log;
         }         
    
         # Feed --------------------------------------------------------------------------------
         location ~* \.(?:rss|atom)$ {
           expires 1h;
           add_header Cache-Control "public";
         }     
    
         # Media: images, icons, video, audio, HTC ---------------------------------------------
         location ~* \.(?:jpg|jpeg|gif|png|ico|cur|gz|svg|svgz|mp4|ogg|ogv|webm|htc)$ {
           expires 1M;
           access_log off;
           add_header Cache-Control "public";
         }         
    
         # CSS and Javascript ------------------------------------------------------------------
         location ~* \.(?:css|js)$ {
           expires 1y;
           access_log off;
           add_header Cache-Control "public";
         }         
    
         # WebFonts ----------------------------------------------------------------------------
         # If you are NOT using cross-domain-fonts.conf, uncomment the following directive
         # location ~* \.(?:ttf|ttc|otf|eot|woff|woff2)$ {
         #  expires 1M;
         #  access_log off;
         #  add_header Cache-Control "public";
         # }
    }
    

    对于本地开发来说,设置缓存 negatito (-1) 以始终更新以加载页面是一个不错的选择。

    请注意,此处显示的配置只是一个示例,您可以(也可以不)使用它们。

    另请注意,通过定义根目录,我将“your_path_here”替换为您的真实目录名称。

    此目录必须在“C:/nginx/html/”中的文件夹“html”内。

    要为“site1”创建一个服务器块,请在“sites-enabled”中创建一个具有任何名称的新配置文件并指向相应的根目录,假设您的主机文件(“C:/Windows/System32/drives /etc/") 将 "site1" 设置为 "127.0.0.1" 或子域设置为 localhost (127.0.0.1 site1.localhost)

    【讨论】:

    • 谢谢劳罗。我已经编辑了这个 nginx.conf 并且它可以正确加载。 localhost 有效,但子站点目录有 404。
    • php_cgi 调用是 "php-cgi.exe -b 127.0.0.1:9000 -c H:\project-tools\php-7.0.10\php.ini" .
    • index.php 包含" "
    • 由于某种原因,它没有打开 localhost/index.php,而是请求下载文件。
    • 很难假设答案适用于他们的情况,因为显然您在不同的目录中运行可执行文件。我在 Windows8 中使用 nginx 1.11.3 和 php 7.0.10 nts。系统驱动器(C :) 上的 Nginx 和 nginx 内的子目录中的 php。我将编辑答案并以我使用的配置为例。可能会有所帮助。
    【解决方案2】:

    我用

     location ~ \.php$ { 
            root           html; 
            fastcgi_pass   127.0.0.1:9000; 
            fastcgi_index  index.php; 
            fastcgi_param  SCRIPT_FILENAME  C:/nginx-0.7.60/html$fastcgi_script_name; #this is the one line for edition 
            include        fastcgi_params; 
        } 
    

    C:\PHP5\php-cgi.exe -b 127.0.0.1:9000

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-10-15
      • 1970-01-01
      • 2015-05-21
      • 2016-04-22
      • 1970-01-01
      • 1970-01-01
      • 2015-02-19
      • 2015-09-26
      相关资源
      最近更新 更多