Common configuration of nginx

joker 2021-02-23 16:08:24
common configuration nginx


alt

nginx What can be done ?

Access control 、 Static resource server 、 Reverse proxy 、 Load balancing 、 Static resource merging

1.nginx Introduction and environmental preparation

nginx It's a lightweight model HTTP The server , Using event driven asynchronous non blocking processing framework , This makes it have excellent IO performance , Often used for reverse proxy and load balancing on the server side

  • install
# Where is the software installed which nginx
# see nginx Whether the configuration is correct :nginx -t
# Check to see if there is Nginx The process of :ps -ef | grep nginx
# Check to see if there is 80 port :netstat -ntl netstat -lntp
# Bully delete process :killall nginx
$ yum install nginx
 Copy code 
  • centos6, You can use the following command

Old leaf mac:/usr/local/nginx/sbin

 start-up :nginx
restart :nginx -s reload
see ng Configuration status :nginx -t
see ng Configuration information :nginx -T
see ng Process information :ps -ef | grep nginx
Check to see if there is 80 port :netstat -ntl
View current port usage :netstat -anp |grep 6000
// Delete
ps -ef | grep nginx // Check the progress
kill -QUIT 15800 // Stop the process calmly id:15800, It doesn't stop immediately
Kill -TERM 15800 // Stop at once
Kill -INT 15800 // Same as above , It's also an immediate stop
killall nginx // Bully delete process
 Copy code 
  • centos7 Can be used later systemctl To manage
 stop it ng: systemctl stop nginx.service
start-up ng:systemctl start nginx.service
restart ng:systemctl restart nginx.service
see ng state :systemctl status nginx.service
Set boot up :systemctl enable nginx.service
Cancel boot service :systemctl disable nginx.service
 Copy code 

2. Access control

nginx -t View profile path

(1) Simple access control

Enter current nginx The configuration file ( The path of Xiaobian is :/etc/nginx/conf.d/default.conf), Add the following configuration :

location / {
deny 10.200.240.219; // This is not allowed ip visit , Designated as all, Can stop all ip visit
allow 10.200.202.231; // Only this is allowed ip visit
}
 Copy code 

Be careful : Two permission instructions under the same block , The first setting will override the later one , for example :

// The following configuration shows : Reject all ip visit
location / {
deny all; //all, Can stop all ip visit
allow 10.200.202.231; // This one is because it appears in deny all after , So it doesn't work
}
// The following configuration shows : Only 10.200.202.231 visit
location / {
allow 10.200.202.231; // This one is because it appears in deny all Before , So allow this ip visit
deny all; // except allow Of ip You can visit , Other ip Access denied
}
 Copy code 

(2) Precise access control

such as : For www Directory is running all user access , But for admin The directory only allows the company's intranet to be fixed IP visit

location =/www{
allow all; // There's no secret , Look around
}
location =/admin{
deny 10.200.240.219; // Like backstage admin Management system , You can only visit it by yourself
}
 Copy code 

And such as : company java Of jsp file , Only intranet ip visit , In this way, people can't see it .jsp The file at the end of the file .

location ~\.jsp$ {
allow 10.200.240.219;
deny all;
}
 Copy code 

End of configuration , Remember Restart it nginx service

3. Set up single or multiple virtual machines

  • a. Go to the main directory :/etc/nginx/nginx.conf

---- Or go to a subdirectory :/etc/nginx/conf.d/default.conf
---- Or in conf.d Next, create a new profile , Can be read to ( The main configuration needs to be included )

  • b. server_name You can set up this machine (localhost)、ip Address (10.200.240.219)、 domain name (baidu.com) etc.
// Configuration based on port number
server {
listen 80;
server_name localhost;
error_page 500 502 503 504 /50x.html;
location / {
index index.html index.htm;
# Read the project directory html80 Under the index.html file
root < Your own project path >/html80
# Reverse proxy local 8080 application
proxy_pass http://127.0.0.1:8080;
}
}
server {
listen 8080;
server_name localhost;
error_page 500 502 503 504 /50x.html;
location / {
# Read the project directory html8080 Under the index.html file
root < Your own project path >/html8080
index index.html index.htm;;
}
}
//------------------------------------------------------------------------------------------
// Based on the domain name configuration example
server {
listen 80;
server_name www.aa.com;
location /api/ {
proxy_pass http://; # Reverse proxy to other sites
}
}
server {
listen 80;
server_name www.bb.com;
location /api/ {
proxy_pass http://localhost:8002; # Reverse proxy to other sites
}
}
 Copy code 

be based on Nginx Virtual host configuration implementation ,Nginx There are three types of virtual hosts

  • be based on IP Virtual host of : Need more than one address on your server , Each site corresponds to a different address , This way is less used

  • Port-based virtual hosts : Each site corresponds to a different port , Use ip:port Mode of access , You can modify listen To use

  • Domain based virtual host : The most widely used way , The above example is based on the domain name of the virtual host , The premise is that you have multiple domain names corresponding to each site ,server_name Just fill in different domain names

  • c. One service configures multiple sites

server {
listen 80;
server_name a.ops-coffee.cn;
location / {
root /home/project/pa;
index index.html;
}
}
server {
listen 80;
server_name ops-coffee.cn b.ops-coffee.cn;
location / {
root /home/project/pb;
index index.html;
}
}
server {
listen 80;
server_name c.ops-coffee.cn;
location / {
root /home/project/pc;
index index.html;
}
}
 Copy code 
  • d. A site is configured with multiple domain names
server {
listen 80;
server_name ops-coffee.cn b.ops-coffee.cn;
}
 Copy code 

4. Reverse proxy

Main configuration location Modular proxy_pass

Generally, the reverse proxy is configured with a ip Address , Because if you configure a domain name , I have to walk again dns analysis , It is not necessary to
The following example accesses http://localhost, In fact, it's a visit http://localhost:8080

server {
listen 80;
server_name localhost;
error_page 500 502 503 504 /50x.html;
location / {
proxy_pass http://localhost:8080; # Reverse proxy to other web The server
}
}
 Copy code 

Other reverse proxy configuration items :

  • proxy_set_header : Before sending client requests to back-end servers , Change request header information from client .
  • proxy_read_timeout : To configure Nginx Issued to back-end server group read After the request , Wait for the corresponding timeout .
  • proxy_send_timeout: To configure Nginx Issued to back-end server group write After the request , Wait for the corresponding timeout .
  • proxy_connect_timeout: To configure Nginx Timeout for an attempt to establish a connection with a back-end proxy server .
  • proxy_redirect : Used to modify the Location and Refresh.

for example :

proxy_set_header Host $http_host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header REMOTE-HOST $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
 Copy code 

4.1 Reverse proxy resolution js Cross domain

So we're going to make a normal request :http://a.com/api/getHomeData Will be forwarded to b.com/api/getHome… In this way, it won't be caused by different domain names js Cross domain .

server {
listen 80;
server_name a.com;
error_page 500 502 503 504 /50x.html;
location /api {
proxy_pass http://b.com/api
}
}
 Copy code 

4.2url Of / problem

stay nginx Middle configuration proxy_pass when , When in the back url Combined with the /, It's the absolute root path , be nginx Will not put location The matching path part of the proxy goes ; without /, It will also give the matching path part to the agent .

  • In the following four cases, we use http://192.168.1.4/proxy/test.html Visit .
# 1. Will be represented to http://127.0.0.1:81/test.html This url
location /proxy/ {
proxy_pass http://127.0.0.1:81/;
}
# 2. Second, we ( Compared to the first , Finally, one less /), Will be represented to http://127.0.0.1:81/proxy/test.html This url
location /proxy/ {
proxy_pass http://127.0.0.1:81;
}
# 3. Will be represented to http://127.0.0.1:81/ftlynx/test.html This url.
location /proxy/ {
proxy_pass http://127.0.0.1:81/ftlynx/;
}
# 4. The fourth situation ( Compared to the third , Finally, one less / ): Will be represented to http://127.0.0.1:81/ftlynxtest.html This url
location /proxy/ {
proxy_pass http://127.0.0.1:81/ftlynx;
}
 Copy code 

5. nginx distinguish PC Mobile or mobile

  • nginx Through built-in variables $http_user_agent, You can get the request client's userAgent, And then judge whether the mobile terminal is PC End , The control returned to the customer is PC Version or H5 edition , This is also the solution of many companies at present
  • The following configuration allows http://localhost:8080 In the mobile environment , Read mobile Website content under ( Default read PC Website content under )
// Commonly used -- according to UA Do redirection
server{
listen 8080;
server_name localhost;
root /Users/joker/2019/pc;
if ($http_host !~ "^www.aa.com$") {
rewrite ^(.*) http://www.aa.com$1 permanent;
}
if ($http_user_agent ~* '(Android|webOS|iPhone|iPod|BlackBerry)') {
rewrite ^(.*) http://m.aa.com$1 permanent;
}
}
// Not commonly used -- Put two copies of code on the same server
server{
listen 8080;
server_name localhost;
location / {
root /Users/joker/2019/pc;
if ($http_user_agent ~* '(Android|webOS|iPhone|iPod|BlackBerry)') {
root /Users/joker/2019/mobile;
}
index index.html;
}
}
 Copy code 

6. Load balancing

Main configuration upstream and location Modular proxy_pass

upstream test_pool{
ip_hash;
server 127.0.0.1:8001 weight=10; # Set access weight , The higher the weight, the easier it is to be accessed
server 127.0.0.1:8002 weight=10;
server 127.0.0.1:8003 weight=7;
}
server {
listen 80;
server_name test.a.com;
location / {
proxy_pass http://test_pool; # Reverse proxy to other server collections
}
}
 Copy code 

ip_hash: Use ip_hash Policy load balancing solution session problem . Per request by access ip Of hash Result distribution , In this way, each visitor has fixed access to a back-end server , It can solve the problem better session The problem of .

7. Static resource request merge

nginx-http-concat

8. location That thing about

rewrite

location ~ \.php${
rewirte "^/php/(.*)$" http://localhost:8001/$1
}
 Copy code 

take localhost/php/test.php Redirect to localhost:8090/test.php. If regular expressions (regex) Match to the requested URI(request URI), This URI It will be replacement Replace
Optional flag The parameters are as follows :

  • last

End the current request processing , Replace it with URI Rematch location;
It can be understood as rewriting (rewrite) after , A new request was made , Get into server modular , matching location;
If the number of rematch cycles exceeds 10 Time ,nginx Returns the 500 error ;
return 302 http Status code ;
The browser address bar shows the reset backward url

  • break

End the current request processing , Use the current resource , Not in execution location The rest of the sentence in ;
return 302 http Status code ;
The browser address bar shows the reset backward url

  • redirect

A temporary jump , return 302 http Status code ;
The browser address bar shows the reset backward url

  • permanent

Jump forever , return 301 http Status code ;
The browser address bar shows the reset backward url

try_files

try_files The instruction is to detect the existence of files in order , And return the content of the first found file , If the first one can't be found, it will automatically find the second one , Search for . What it realizes is internal jump

# example01: Jump to variable
server {
listen 8000;
server_name 121.10.143.66;
root html;
index index.html index.php;
location /abc {
try_files /4.html /5.html @qwe; ## Test files 4.html and 5.html, If there is a normal display , If it doesn't exist, look for it @qwe value
}
location @qwe {
rewrite ^/(.*)$ http://www.baidu.com; ## Jump to Baidu page
}
}
# example02: Jump to specified file , If it doesn't exist, look back , Found the display . Test link :http://121.10.143.66:8000/abc
server {
listen 8000;
server_name 121.10.143.66;
root html;
index index.php index.html;
location /abc {
try_files /4.html /5.html /6.html;
}
}
 Copy code 
版权声明
本文为[joker]所创,转载请带上原文链接,感谢
https://qdmana.com/2021/02/20210223155148558K.html

  1. Are airpods still the strongest? Horizontal evaluation of 4 true wireless headphones
  2. Seamless connection with tableau, how can this large bank with 5000 + active users realize self-service analysis?
  3. react-native版文字跑马灯
  4. React native text running lantern
  5. Java、JavaScript、C、C++、PHP、Python都是用来开发什么?
  6. What are Java, JavaScript, C, C + +, PHP and python used to develop?
  7. this.byId(SupplierForm).bindElement in SAP UI5
  8. SAP UI5 JavaScript文件的lazy load - 懒加载
  9. this.byId (SupplierForm).bindElement in SAP UI5
  10. Lazy load lazy load of SAP ui5 JavaScript files
  11. "Gnome 3" - interface elements, desktop components, part names (learning notes) @ 20210223
  12. How to connect the ground gas to the micro front end?
  13. How to transform single / micro service application into serverless application
  14. 在 2021 年你需要掌握的 7 种关于 JavaScript 的数组方法
  15. Seven array methods for JavaScript you need to master in 2021
  16. 在 2021 年你需要掌握的 7 种关于 JavaScript 的数组方法
  17. Seven array methods for JavaScript you need to master in 2021
  18. 在 2021 年你需要掌握的 7 种关于 JavaScript 的数组方法
  19. Seven array methods for JavaScript you need to master in 2021
  20. RxHttp - 轻量级、可扩展、易使用、完美兼容MVVM、MVC架构的网络封装类库
  21. RxHttp - 轻量级、可扩展、易使用、完美兼容MVVM、MVC架构的网络封装类库
  22. Rxhttp - lightweight, extensible, easy to use, perfectly compatible with MVVM, MVC architecture network encapsulation class library
  23. Rxhttp - lightweight, extensible, easy to use, perfectly compatible with MVVM, MVC architecture network encapsulation class library
  24. 前端面试常考题:JS垃圾回收机制
  25. Frequently asked questions in front end interview: JS garbage collection mechanism
  26. Rxhttp - lightweight, extensible, easy to use, perfectly compatible with MVVM, MVC architecture network encapsulation class library
  27. Java之HTTP网络编程(一):TCP/SSL网页下载
  28. HTTP network programming in Java (1): TCP / SSL web page download
  29. Java之HTTP网络编程(一):TCP/SSL网页下载
  30. HTTP network programming in Java (1): TCP / SSL web page download
  31. 使用vite搭建vue项目
  32. 在组件中展示pdf文件:vue-pdf (由于未找到方法滑动加载下一页,只能点击加载下一页pdf文件)
  33. 在 vue 中通过 express 连接数据库
  34. Using vite to build Vue project
  35. Display PDF file in component: Vue pdf
  36. Connecting database through express in Vue
  37. 2021届秋招哈啰出行前端面经(一面)
  38. vue使用sdk进行七牛云上传
  39. Javascript性能优化【内联缓存】 V8引擎特性
  40. Small true wireless smart headset evaluation: put intelligence into the ear
  41. The front end experience of the 2021 autumn recruitment
  42. Vue uses SDK to upload Qi Niu cloud
  43. 深入理解 Web 协议 (三):HTTP 2
  44. dhtmlxGantt如何重新排序任务
  45. JavaScript performance optimization [inline cache] V8 engine features
  46. 深入理解 Web 协议 (三):HTTP 2
  47. Deep understanding of Web protocol (3): http 2
  48. 深入理解 Web 协议 (三):HTTP 2
  49. How dhtmlxgantt reorders tasks
  50. 深入理解 Web 协议 (三):HTTP 2
  51. JavaScriptBOM操作
  52. JavaScriptBOM操作
  53. Deep understanding of Web protocol (3): http 2
  54. Deep understanding of Web protocol (3): http 2
  55. dhtmlxGantt甘特图重新排序任视频教程
  56. vue实现七牛云上传图片功能
  57. vue.js环境配置步骤及npm run dev报错解决方案
  58. Deep understanding of Web protocol (3): http 2
  59. JavaScript BOM operation
  60. JavaScript BOM operation