HTTP核心模块配置静态web服务器 2-文件路径的定义

来源:互联网 发布:淘宝上卖工艺品好卖吗 编辑:程序博客网 时间:2024/06/05 17:29
2,文件路径的定义
2-1 以root方式设置资源路径
语法:root path;
默认:root html;
配置块:http,server,location,if
例如:定义资源文件相对于http请求的根目录
location /download/ {
       root /opt/web/html/;
}
在上边的配置中,如果有一个请求的URI是/download/index/test.html,那么web服务器将会返回服务器上/opt/web/html/index/test.html的文件
2-2 以alias方式设置资源路径
语法:alias path;
配置块:location
例如:请求URI是/conf/nginx.conf,用户实际想访问/usr/local/nginx/conf/nginx.conf,那么使用alias
      location /conf {
             alias /usr/local/nginx/conf/;
    }
alias必须以/结束,如果使用root配置,如下:
  location /conf {
             root /usr/local/nginx/;
    }
alias后面还可以添加正则表达式。
2-3 访问首页
语法:index file ....;
默认:index index.html;
配置块:http,server,location
一般访问站点URI是/时,返回首页。这里用ngx_http_index_module模块提供的index配置实现。index后可以跟多个文件参数,nginx将会按照顺序来访问这些文件,例如:
location / {
    root path;
    index /index.html /html/index.php
}
收到请求后,nginx会尝试访问path/index.html,如果可以直接返回,否则再试图访问path/html/index.php
2-4 根据HTTP返回码重定向页面
语法:error_page code[code...][=|=answer-code]uri|@named_location
配置块:http,server,location,if
当对于某个请求返回错误码时,如果匹配上了error_page中设置的code,则重定向到新的URI中。例如:
error_page  404  /404.html
error_page  502 503 504  /50x.html
error_page  403  http://ex 
error_page  404 = @fet
注意,虽然重定向了URI,但返回的HTTP错误码还是与原来的相同。用户可以通过"="来更改返回的错误码,例如:
error_page  404  =200  /empty.gif;
error_page  404  =403  /forbidden.gif;
也可以不指定确切的返回错误码,而是由重定向后实际处理的真实结果来决定,这时,只要把“=”后边的错误码去掉即可,例如:
error_page  404  =  /empty.gif;
如果不想修改URI,只是想让这样的请求重定向到另一个location中进行处理,那么可以这样设置:
location / {
      error_page  404  @fallback;
}
location @fallback {
      proxy_pass http://backend; 
}
2-5 是否允许递归使用error_page
语法:recursive_error_pages [on|off]
默认:recursive_error_pages off;
配置块:http,server,location
2-6 try_files
语法:try_files path1[path2]uri;
配置块:server,location
try_files后要跟若干路径,如:path1 path2 ...,而且最后必须带参数uri,意义如下:尝试按照顺序访问每一个path,如果可以有效的读取,就直接返回,否则,继续向下访问。如果所有的path都找不到有效文件,就重定向到最后的URI上,这个必须存在。
例如:
try_files /system/maintenance.html
location @other {
     proxy_pass http://backend; 
}
如果/system/maintenance.html找不到,就反向代理至http://backend ,还可以用指定错误码的方式与error_page配合使用,例如:
location / {
     try_files $uri $uri/ /error.php c=
}
0 0
原创粉丝点击