Skip to content

Instantly share code, notes, and snippets.

@webstrand
Created May 10, 2024 14:31
Show Gist options
  • Save webstrand/2e85f25ef2f7671ecd1d177374927aba to your computer and use it in GitHub Desktop.
Save webstrand/2e85f25ef2f7671ecd1d177374927aba to your computer and use it in GitHub Desktop.
Portable nginx reverse proxy with CORS override
#!/usr/bin/env -S nginx -e /dev/stderr -p . -c
# Run an NGINX instance serving the current directory on ports 8080 and 8443
# (when configured). Execute one of the following commands in the terminal.
# - start-nodaemon: ./nginx.conf -g 'daemon off;'
# - start: ./nginx.conf
# - stop: ./nginx.conf -s stop
# - reload: ./nginx.conf -s reload
pid .nginx/nginx.pid;
events {}
http {
include /etc/nginx/mime[.]types; # Linux
include /usr/local/etc/nginx/mime[.]types; # OSX/homebrew
default_type application/octet-stream;
types {
application/javascript mjs;
}
access_log .nginx/http.access.log;
error_log .nginx/http.error.log;
client_body_temp_path .nginx/client_body;
fastcgi_temp_path .nginx/fastcgi;
proxy_temp_path .nginx/proxy;
scgi_temp_path .nginx/scgi;
uwsgi_temp_path .nginx/uwsgi;
# Set the Content-Length header for OPTIONS requests
map $request_method $override_content_length { default ''; OPTIONS 0; }
ssl_protocols TLSv1.3;
server {
root .;
listen 8080;
listen [::]:8080;
# Be sure to generate the necessary certificates before enabling SSL:
#
# openssl req -new -x509 -days 7300 -nodes -newkey rsa:2048 -out \
# .nginx/snakeoil.pem -keyout .nginx/snakeoil.key -subj \
# "/C=ZZ/O=Snakeoil Cert"
#listen 8443 ssl;
#listen [::]:8443 ssl;
#ssl_certificate .nginx/snakeoil.pem;
#ssl_certificate_key .nginx/snakeoil.key;
location /api/ {
proxy_pass https://example.com/;
proxy_ssl_server_name on;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
# CORS headers
add_header 'Access-Control-Allow-Origin' 'https://localhost:3000' always;
add_header 'Vary' 'origin' always;
add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS, PUT, DELETE' always;
add_header 'Access-Control-Allow-Headers' 'Authorization, Content-Type, Accept, Origin, X-Requested-With' always;
add_header 'Access-Control-Allow-Credentials' 'true' always;
# Handle CORS preflight requests
if ($request_method = 'OPTIONS') {
add_header 'Access-Control-Max-Age' 1728000;
add_header 'Content-Type' 'text/plain charset=UTF-8';
add_header 'Content-Length' 0;
return 204;
}
}
}
}
# source: https://gist.github.com/webstrand/2389c00cb7a5418ac0119e3451a97056
# CORS rules source: https://michielkalkman.com/snippets/nginx-cors-open-configuration/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment