在nginxconfiguration中省略重复

我有一个非常简单的nginx所以我的本地服务可以很好地从外面访问。

这是configuration

 user httpdusr everyone; ##################### worker_processes 1; events { worker_connections 1024; } http { server { listen 80; include /opt/etc/nginx/mime.types; location / { try_files $uri$args $uri$args/ index.html; root /share/CE_CACHEDEV1_DATA/Web/fitness/; } auth_basic "Restricted"; auth_basic_user_file /share/Web/.htpasswd } server { listen 80; server_name service1.domain.com; location / { proxy_pass http://localhost:9091; } } server { listen 80; server_name service2.domain.com; location / { proxy_pass http://localhost:8080; } } server { listen 80; server_name service3.domain.com; location / { proxy_pass http://192.168.1.1; } proxy_set_header Host $host; } server { listen 80; server_name service4.domain.com; location / { proxy_pass http://localhost:32400; } } server { listen 80; server_name service5.domain.com; location / { proxy_pass http://localhost:5601; } auth_basic "Restricted"; auth_basic_user_file /share/Web/.htpasswd; } } 

我不是NGINX专家,这是我想出了几个教程。 但是,正如你所看到的,服务的数量正在增长,重复性越来越大。 作为一名开发人员…它伤害了我内心:-)

我知道这是可能的,但我不知道如何得到一个共同的部分,如:

 common() { listen 80; server_name <param1>; location / { proxy_pass <param2>; } } 

然后像使用它

 common(service1.domain.com, http://localhost:9091) 

谢谢!

你可以使用Nginx的include函数,但是你不能做参数。 我不知道有什么办法可以实现你想要的,除了可能是一些自制的模板系统。 我不会打扰。

长的Nginxconfiguration文件很好,而且维护方便。 一旦达到成千上万条线路变得越来越难以pipe理,但在您的规模,这通常是没有问题的。

对于组织来说,最好每个域都有一个文件,http / https所需的服务器块,子域等等。主要的Nginx文件包含它们。 您可以在configuration文件中包含完全相同的代码,如下所示。

/etc/nginx/nginx.conf

 include /etc/nginx/enabled-sites/*; 

/etc/nginx/enabled-sites/site1.conf

 server { location / { // etc } include /etc/nginx/fragments/security-headers; } 

的/ etc / nginx的/片段/安全报头

 # Security headers add_header Strict-Transport-Security "max-age=2592000; includeSubDomains; preload"; add_header X-Frame-Options DENY; add_header X-Content-Type-Options nosniff; add_header Content-Security-Policy "default-src 'self' www.google-analytics.com ajax.googleapis.com www.google.com google.com gstatic.com www.gstatic.com connect.facebook.net facebook.com;"; add_header X-XSS-Protection "1; mode=block"; add_header Referrer-Policy "origin";