静态资源

把静态资源放在nginx服务器,index.html放在别的服务器
配置如下

  1. #user nobody;
  2. worker_processes 1;
  3. events {
  4. worker_connections 1024;
  5. }
  6. http {
  7. include mime.types;
  8. default_type application/octet-stream;
  9. #access_log logs/access.log main;
  10. sendfile on;
  11. keepalive_timeout 65;
  12. server {
  13. listen 80;
  14. server_name localhost;
  15. location / {
  16. proxy_pass 10.211.55.6;
  17. }
  18. location /js {
  19. root html;
  20. index index.html index.htm;
  21. }
  22. location /img {
  23. root html;
  24. index index.html index.htm;
  25. }
  26. location /css {
  27. root html;
  28. index index.html index.htm;
  29. }
  30. error_page 500 502 503 504 /50x.html;
  31. location = /50x.html {
  32. root html;
  33. }
  34. }
  35. }

location正则匹配

  1. location ~*/(js|img|css) {} # 上面的location配置可以用这个正则实现

location 前缀
/ 通用匹配,任何请求都会匹配到。
= 精准匹配,不是以指定模式开头
~ 正则匹配,区分大小写
~ 正则匹配,不区分大小写
^~ 非正则匹配,匹配以指定模式开头的location
*location匹配顺序

  • 多个正则location直接按书写顺序匹配,成功后就不会继续往后面匹配
  • 普通(非正则)location会一直往下,直到找到匹配度最高的(最大前缀匹配)
  • 当普通location与正则location同时存在,如果正则匹配成功,则不会再执行普通匹配
  • 所有类型location存在时,“=”匹配 > “^~”匹配 > 正则匹配 > 普通(最大前缀匹配
    1. location ~*/(css|img|js) {
    2. root /usr/local/nginx/static;
    3. index index.html index.htm;
    4. }

alias与root

  1. location /css {
  2. alias /usr/local/nginx/static/css;
  3. index index.html index.htm;
  4. }

root用来设置根目录,而alias在接受请求的时候在路径上不会加上location。

  • alias指定的目录是准确的,即location匹配访问的path目录下的文件直接是在alias目录下查找的;
  • root指定 的目录是location匹配访问的path目录的上一级目录,这个path目录一定要是真实存在root指定目录下的;
  • 使用 alias标签的目录块中不能使用rewrite的break(具体原因不明);另外,alias指定的目录后面必须要加上”/“符 号!!
  • alias虚拟目录配置中,location匹配的path目录如果后面不带”/“,那么访问的url地址中这个path目录后 面加不加”/“不影响访问,访问时它会自动加上”/“; 但是如果location匹配的path目录后面加上”/“,那么访问的url地 址中这个path目录必须要加上”/“,访问时它不会自动加上”/“。如果不加上”/“,访问就会失败!
  • root目录配置 中,location匹配的path目录后面带不带”/“,都不会影响访问。

    伪静态配置

    1. location / {
    2. rewrite^/([0-9]+).html$ /index.jsp?pageNum=$1 break;
    3. proxy_pass 10.211.55.6;
    4. }