Skip to content

Instantly share code, notes, and snippets.

@AhmedAbouelkher
Last active February 6, 2023 13:45
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save AhmedAbouelkher/b9a1563f3235272f224ec4b5752cfbc0 to your computer and use it in GitHub Desktop.
Save AhmedAbouelkher/b9a1563f3235272f224ec4b5752cfbc0 to your computer and use it in GitHub Desktop.
A demo code to test [Handling CORS in Nginx as a reverse proxy]
package main
import (
"net/http"
"github.com/rs/cors"
)
func main() {
mux := http.NewServeMux()
mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
w.Write([]byte("Hello World"))
})
r := cors.AllowAll().Handler(mux)
http.ListenAndServe(":3000", r)
}
# Server Configrations
#
server {
listen 80;
server_name example.com;
location / {
proxy_pass http://localhost:3000;
# Handling OPTIONS for this location directive.
if ($request_method = 'OPTIONS') {
add_header Access-Control-Allow-Origin "$http_origin";
add_header Access-Control-Allow-Credentials 'true';
add_header Access-Control-Allow-Headers 'Authorization, Content-Type, Origin, X-Requested-With, Accept';
add_header Access-Control-Allow-Methods 'GET, POST, OPTIONS, PUT, DELETE';
add_header Content-Type 'text/plain; charset=utf-8';
return 204;
}
proxy_set_header X-Original-URI $request_uri;
proxy_set_header X-Original-Remote-Addr $remote_addr;
proxy_set_header X-Original-Host $host;
}
}
# vim: syntax=nginx
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment