问题原文
原帖链接 · Atais · CC BY-SA 3.0
I have a very simple nginx so my local services can be nicely accessed from outside.
This is the config
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;
}
}
I am no NGINX expert, this is what I came up with a couple of tutorials. However, as you can see, the number of services is growing and the repetition is getting bigger and bigger. Being a developer... it hurts me inside :-)
I know it is possible, but I do not know how to get a common part like:
common() {
listen 80;
server_name <param1>;
location / {
proxy_pass <param2>;
}
}
and then use it like
common(service1.domain.com, http://localhost:9091)
Thanks!
已采纳解答
原帖链接 · Tim · CC BY-SA 3.0
You can use the Nginx include function, but you can't do parameters. I don't know any way to achieve exactly what you want, other than perhaps some home grown template system. I wouldn't bother.
Long hand Nginx configuration files are fine, and easy to maintain. Once they reach thousands of lines becomes more difficult to manage, but at your scale it's typically no problem.
For organisation, it's good to have one file per domain, with as many server blocks as are required for http / https, subdomains, etc. The main Nginx file includes them. You can include code that is exactly the same between config files, as below.
/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/fragments/security-headers
# 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";
摘自公开归档,保留原文语言,版式经整理,外部媒体与邮箱地址已移除。
