High-performance web container Nginx
Nginx, like Apache and Tomcat, is an HTTP server. Their essence is still an application, placed on the server side, and listens to a port to accept the client's HTTP request by binding ip:port. According to the classification of dynamic/static servers, Nginx and Apache are static servers, and Tomcat and jetty are dynamic servers.
Nginx configuration details
The nginx.config configuration file mainly consists of main, event, http and other modules. Let’s talk about the configuration of http in detail.
Virtual host configuration
There are three types of virtual host configurations: IP-based virtual host, port-based virtual host and domain name-based virtual host. Generally speaking, port-based and domain-name-based virtual hosts are more commonly used.
-
Port-based virtual host configuration
server { listen 80; server_name location; location / { root html; index index.html; } }
-
Domain name based virtual hosting
server{ listen 80; server_name mes.action-prowave.com; location / { root html; index mes.html }
}
```
location configuration syntax
location [ = | ^~ | ~*] /uri/ {……}
location = /uri (exact match, highest priority)
location ^~ /uri (normal match, second priority)
location ~ /uri (regular match)
location = /
location = /index
location ^~/article
location ^~/article/file
location ~ \.(PNG | GIF)$
actual use
location = / {
//主页配置
}
location / {
//通用配置
}
location / {
//静态文件配置
}
reverse proxy
server{
listen 80;
server_name localhost;
location / {
proxy_pass http://192.168.0.45:8080;
proxy_set_header Host $host; //host变量
proxy_set_header X-Real -IP $remote_addr;//远程地址
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;//所有代理服务器的地址
}
}
load balancing
upsteam tomcat{
server 192.168.0.1 max-fails=2 fail_timeout 60s;(最大失败次数,失败后60s内不再发送请求);
server 192.168.0.2;
}
server{
listen 80;
server_name localhost;
location / {
proxy_pass http://tomcat;
proxy_next_upsteam error timeout http_500;(服务器出现错误的时候向其他服务器发送请求)
proxy_connect_timeout 60s;(nginx与上游服务器的连接超时时间,默认60s)
proxy_send_timeout 60s;
proxy_read_timeout 60s;
}
}
Separation of movement and stillness
```
location ~ .*\.(js|css|png|svg|ico|jpg)${
root static-resource;
}
```
File compression
http {
gzip on;
gzip_min_length 5k; //压缩的最小长度,当超过该长度的时候需要进行压缩
gzip_comp_level 3; //压缩等级,级别越高,文件压缩的越小,会带来CPU资源的占用
gzip_types application/javascript image/jpeg //哪些类型的文件需要压缩
gzip_buffers 4 32K; //以32k的4倍去申请内存
gzip_vary on; //根据http头判断是否进行压缩
}
Anti-hotlinking
location ~ .*\.(js|css|png|svg|ico|jpg)${
valid_referers none blocked 192.168.0.4 www.action-prowave.com;
if ($invalid_referer) {
return 404;
}
root static-resource;
}
Cross-domain access
location / {
add_header Access-Controller-Allow-Origin *;
add_header Access-Controller-Allow-Methods 'GET,POST,OPTIONS';
add_header Access_Controller-Allow-Header 'Content-type';
}