nginx虚拟主机的配置

                                             nginx虚拟主机的配置                                          

server {
        listen       80;
        server_name  127.0.0.1;
        access_log   off;

        root /var/www/html/;
        location / {
        index index.php index.html index.htm;
        try_files $uri $uri/ /index.php?$args;    
        ##$uri代表请求的文件或文件夹。$args这个变量等于请求行中的参数。 
}

        location ~ .*.(php|php5)?$ {
                try_files $uri =404;               #不懂为什么
                fastcgi_pass    127.0.0.1:9000;
                fastcgi_index   index.php;
                fastcgi_param  SCRIPT_FILENAME  $document_root$fastcgi_script_name;  #不懂为什么
                #$document_root当前请求在root指令中指定的值.    
                include         fastcgi.conf;
}

        location ~ .*.(gif|jpg|jpeg|png|bmp|swf)$
                { 
                  root    /data/nginx/cache;   ##配置文件所在的目录,或者是缓存目录。
                  expires      15d;
                }
                 
        location ~ .*.(js|css)?$
                { 
                  expires      1h;
                }
}

以上虚拟主机的配置详解:

  • location 定义文件类型, .php$ 代表所有以 php 作为文件后缀的文件类型.
  • root 定义 php 文件存放的路径, 当前以 变量$document_root来获取网站根目录的位置。
  • fastcgi_index 定义 php 文件类型中的默认索引页
  • fastcgi_param SCRIPT_FILENAME 定义了页面请求参数, 如客户端需要访问 /test.php 则会自动读取 //test.php文件, 如客户端访问 / 则自动读取 /www/index.php 文件
  • include 定义fastcgi 配置信息将会被保存到 /data/nginx/conf/fastcgi_params 文件中
  •  nginx的try_files指令,当一个请求发生时,比如"/abc",它会检查"/abc"($uri)文件是否存在以及"/abc/"($uri/)目录是否存在,如果不存在,则重定向到最后一个参数"/index.php$$args".
  • index.php是框架的"入口文件"。
  • $uri变量作用解释:请求中的当前URI(不带请求参数,参数位于$args),可以不同于浏览器传递的$request_uri的值,它可以通过内部重定向,或者使用index指令进行修改。
  • try_files       $uri $uri /index.php?$args;    查找url,如果找不到,就重定向。
  • 现在有这样一个需求,网站根目录下有静态文件,static目录下也有静态文件,static目录下的静态文件是程序批量生成的,我想让nginx在地址不变的前提下优先使用static目录里面的文件,如果不存在再使用根目录下的静态文件,比如访问首页http://example.com/index.html则nginx返回/static/index.html,如果不存在返回/index.html。
    set $static "/static";
    try_files $static$uri $static$uri/index.html /index.php;
原文地址:https://www.cnblogs.com/tangshengwei/p/4978345.html