Nginx动静分离配置详解
Nginx动静分离核心配置
#动静分离
server{
listen 80;
server_name cc.com;
access_log off;
location ~* \.(png|jpg|js|css)$ {
proxy_pass http://127.0.0.1:8080;
#所有以.png .html .js .css结尾的url进入此路径 (png|html|js|css)
}
location /{
index index.html index.htm;
proxy_pass http://127.0.0.1:8080/m/;#注意这里的/的含义见下文
}
}
在Nginx中配置proxy_pass代理转发时,如果在proxy_pass后面的url加/,表示绝对根路径;如果没有/,表示相对路径,把匹配的路径部分也给代理走。
完整配置参考
server {
listen 80;
server_name aaa.com;
#access_log logs/web.log main;
#access_log off;
location ~ ^/(WEB-INF)/ {
deny all;
}
#rewrite ^(.*)$ https://$host$1 permanent; #用于将http页面重定向到https页面
#动静分离
location ~* \.(gif|jpg|png|bmp|swf|js|css)$ {
expires 30d; #缓存30天
proxy_pass http://localhost:8080;
#所有以.png .html .js .css结尾的url进入此路径 (png|html|js|css)
}
location / {
root /cycy/web/site/m;
index index.jsp index.html index.htm;
proxy_pass http://localhost:8080/m/;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_redirect off;
client_max_body_size 10m;
client_body_buffer_size 128k;
proxy_connect_timeout 90;
proxy_read_timeout 90;
proxy_buffer_size 4k;
proxy_buffers 6 32k;
proxy_busy_buffers_size 64k;
proxy_temp_file_write_size 64k;
}
gzip on;
gzip_min_length 1k;
gzip_buffers 4 16k;
gzip_http_version 1.0;
gzip_comp_level 2;
gzip_types text/plain application/x-javascripttext/css application/xml;
gzip_vary on;
#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 html;
}
# proxy the PHP scripts to Apache listening on 127.0.0.1:80
#
#location ~ \.php$ {
# proxy_pass http://127.0.0.1;
#}
# pass the PHP scripts to FastCGI server listening on 127.0.0.1:9000
#
#location ~ \.php$ {
# root html;
# fastcgi_pass 127.0.0.1:9000;
# fastcgi_index index.php;
# fastcgi_param SCRIPT_FILENAME /scripts$fastcgi_script_name;
# include fastcgi_params;
#}
# deny access to .htaccess files, if Apache's document root
# concurs with nginx's one
#
#location ~ /\.ht {
# deny all;
#}
}
扩展阅读
基本语法: location [=|~|~*|^~]/uri/{...}
= 严格匹配, 如果这个查询匹配,将停止搜索并立即处理此请求
~ 区分大小写匹配(可用正则表达式)
~* 不区分大小写匹配(可用正则表达式)
!~ 区分大小写匹配
!~* 不区分大小写匹配
^~ 如果把这个前缀用于一个常规字符串