Skip to content

Instantly share code, notes, and snippets.

@amanjuman
Last active August 22, 2020 12:26
Show Gist options
  • Save amanjuman/55349c45d6d35abbca04da3c74673ab6 to your computer and use it in GitHub Desktop.
Save amanjuman/55349c45d6d35abbca04da3c74673ab6 to your computer and use it in GitHub Desktop.
Nginx configuration for adding cross-origin resource sharing (CORS)
server
{
# Listen
listen 80;
listen [::]:80;
#listen 443 ssl http2;
#listen [::]:443 ssl http2;
# Directory & Server Naming
root /var/www/yourdomain.com;
index index.php index.html;
server_name yourdomain.com www.yourdomain.com;
http2_push_preload on;
# HTTP to HTTPS redirection
#if ($scheme != "https")
#{
# return 301 https://$host$request_uri;
#}
# SSL
#ssl_certificate /etc/letsencrypt/live/yourdomain.com/fullchain.pem;
#ssl_certificate_key /etc/letsencrypt/live/yourdomain.com/privkey.pem;
#ssl_trusted_certificate /etc/letsencrypt/live/yourdomain.com/fullchain.pem;
# Disable Hidden FIle Access Except Lets Encrypt Verification
location ~ /\.well-known
{
allow all;
}
# Nginx Logging
access_log /var/log/nginx/yourdomain.com-access.log;
error_log /var/log/nginx/yourdomain.com-error.log warn;
# Max Upload Size
client_max_body_size 100M;
# PHP Upsteam
location ~ \.php$
{
include snippets/fastcgi-php.conf;
## For PHP 7.0
#fastcgi_pass unix:/var/run/php/php7.0-fpm.sock;
## For PHP 7.2
fastcgi_pass unix:/var/run/php/php7.2-fpm.sock;
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
include fastcgi_params;
}
# Permalink Support
location / {
try_files $uri $uri/ /index.php?$args;
}
# Nginx CORS Resource Share
set $cors_origin "";
set $cors_cred "";
set $cors_header "";
set $cors_method "";
# CORS Origin
if ($http_origin ~ '^https?://(localhost|yourdomain\.com)$')
{
set $cors_origin $http_origin;
set $cors_cred true;
set $cors_header $http_access_control_request_headers;
set $cors_method $http_access_control_request_method;
}
# CORS Orgin Condition
add_header Access-Control-Allow-Origin $cors_origin;
add_header Access-Control-Allow-Credentials $cors_cred;
add_header Access-Control-Allow-Headers $cors_header;
add_header Access-Control-Allow-Methods $cors_method;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment