Last active
October 13, 2021 08:00
-
-
Save daimaou92/226631945a3b19f8e610a709abefedf0 to your computer and use it in GitHub Desktop.
nginx template with map for Forwarded Header per RFC 7239
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
map $remote_addr $proxy_forwarded_elem { | |
# IPv4 addresses can be sent as-is | |
~^[0-9.]+$ "for=$remote_addr"; | |
# IPv6 addresses need to be bracketed and quoted | |
~^[0-9A-Fa-f:.]+$ "for=\"[$remote_addr]\""; | |
# Unix domain socket names cannot be represented in RFC 7239 syntax | |
default "for=unknown"; | |
} | |
map $http_forwarded $proxy_add_forwarded { | |
# If the incoming Forwarded header is syntactically valid, append to it | |
"~^(,[ \\t]*)*([!#$%&'*+.^_`|~0-9A-Za-z-]+=([!#$%&'*+.^_`|~0-9A-Za-z-]+|\"([\\t \\x21\\x23-\\x5B\\x5D-\\x7E\\x80-\\xFF]|\\\\[\\t \\x21-\\x7E\\x80-\\xFF])*\"))?(;([!#$%&'*+.^_`|~0-9A-Za-z-]+=([!#$%&'*+.^_`|~0-9A-Za-z-]+|\"([\\t \\x21\\x23-\\x5B\\x5D-\\x7E\\x80-\\xFF]|\\\\[\\t \\x21-\\x7E\\x80-\\xFF])*\"))?)*([ \\t]*,([ \\t]*([!#$%&'*+.^_`|~0-9A-Za-z-]+=([!#$%&'*+.^_`|~0-9A-Za-z-]+|\"([\\t \\x21\\x23-\\x5B\\x5D-\\x7E\\x80-\\xFF]|\\\\[\\t \\x21-\\x7E\\x80-\\xFF])*\"))?(;([!#$%&'*+.^_`|~0-9A-Za-z-]+=([!#$%&'*+.^_`|~0-9A-Za-z-]+|\"([\\t \\x21\\x23-\\x5B\\x5D-\\x7E\\x80-\\xFF]|\\\\[\\t \\x21-\\x7E\\x80-\\xFF])*\"))?)*)?)*$" "$http_forwarded, $proxy_forwarded_elem"; | |
# Otherwise, replace it | |
default "$proxy_forwarded_elem"; | |
} | |
upstream servicename { | |
server localhost:5000; | |
} | |
server { | |
listen 80; | |
listen [::]:80; | |
server_name service.name.example.org; | |
return 301 https://$host$request_uri; | |
} | |
server { | |
listen 443 ssl; | |
listen [::]:443 ssl; | |
server_name service.name.example.org; | |
ssl_certificate /etc/letsencrypt/live/service.name.example.org/fullchain.pem; | |
ssl_certificate_key /etc/letsencrypt/live/service.name.example.org/privkey.pem; | |
charset utf-8; | |
client_max_body_size 75M; | |
location / { | |
proxy_pass http://servicename; | |
proxy_set_header Upgrade $http_upgrade; | |
proxy_set_header Connection 'upgrade'; | |
proxy_set_header Host $host; | |
proxy_set_header Forwarded "$proxy_add_forwarded;proto=$scheme"; | |
proxy_set_header X-Real-IP $remote_addr; | |
proxy_set_header X-Forwarded-Proto $scheme; | |
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; | |
proxy_cache_bypass $http_upgrade; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment