配置nginx以运行子网站

时间:2016-09-28 14:51:41

标签: php nginx

我能够根据教程设置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

潜在的网址应为:

  

本地主机
  本地主机/ SITE1

由于

2 个答案:

答案 0 :(得分:0)

在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(开始|关闭服务)[无法为你服务]

@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;     

 }

请注意,本示例结束时我们“包含”了“sites-enabled”文件夹中的所有文件“.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";
     # }
}

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

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

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

此目录必须位于“C:/ nginx / html /".

中的文件夹”html“内

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

答案 1 :(得分:0)

我使用

 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