How to Enable Cors In NGINX?

11 minutes read

To enable Cross-Origin Resource Sharing (CORS) in NGINX, you can follow these steps:

  1. Open the NGINX configuration file. It is commonly located at /etc/nginx/nginx.conf or /etc/nginx/conf.d/default.conf.
  2. Within the configuration file, find the http block. This is where you can make server-wide changes.
  3. Add the following code inside the http block to enable CORS:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
http {
  ...
  # Enable CORS
  server {
    location / {
      if ($request_method = 'OPTIONS') {
        add_header 'Access-Control-Allow-Origin' '*';
        add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS';
        #
        # Custom headers and headers various browsers *should* be OK with but aren't
        #
        add_header 'Access-Control-Allow-Headers' 'DNT, X-CustomHeader, Keep-Alive, User-Agent, X-Requested-With, If-Modified-Since, Cache-Control, Content-Type';
        #
        # Tell client that this pre-flight info is valid for 20 days
        #
        add_header 'Access-Control-Max-Age' 1728000;
        add_header 'Content-Type' 'text/plain charset=UTF-8';
        add_header 'Content-Length' 0;
        return 204;
      }
      if ($request_method = 'POST') {
        add_header 'Access-Control-Allow-Origin' '*';
        add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS';
        add_header 'Access-Control-Allow-Headers' 'DNT, X-CustomHeader, Keep-Alive, User-Agent, X-Requested-With, If-Modified-Since, Cache-Control, Content-Type';
        add_header 'Access-Control-Expose-Headers' 'Content-Length, X-JSON';
        add_header 'Access-Control-Max-Age' 1728000;
      }
      if ($request_method = 'GET') {
        add_header 'Access-Control-Allow-Origin' '*';
        add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS';
        add_header 'Access-Control-Allow-Headers' 'DNT, X-CustomHeader, Keep-Alive, User-Agent, X-Requested-With, If-Modified-Since, Cache-Control, Content-Type';
        add_header 'Access-Control-Expose-Headers' 'Content-Length, X-JSON';
        add_header 'Access-Control-Max-Age' 1728000;
      }
    }
  }
  ...
}


  1. Save the configuration file and exit the text editor.
  2. Reload or restart NGINX to apply the changes. The command may vary depending on your operating system, but common commands include:
  • sudo service nginx reload
  • sudo systemctl reload nginx
  • sudo /etc/init.d/nginx reload


After following these steps, NGINX should be configured to allow Cross-Origin Resource Sharing for the specified methods. Note that these configuration settings allow any origin (*) to make requests. Adjust the Access-Control-Allow-Origin setting accordingly to restrict it to specific domains if needed.

Best Nginx Books to Ready in 2024

1
Nginx HTTP Server - Third Edition: Harness the power of Nginx to make the most of your infrastructure and serve pages faster than ever

Rating is 5 out of 5

Nginx HTTP Server - Third Edition: Harness the power of Nginx to make the most of your infrastructure and serve pages faster than ever

2
Mastering NGINX Second Edition

Rating is 4.9 out of 5

Mastering NGINX Second Edition

3
NGINX Cookbook: Over 70 recipes for real-world configuration, deployment, and performance

Rating is 4.8 out of 5

NGINX Cookbook: Over 70 recipes for real-world configuration, deployment, and performance

4
Nginx HTTP Server: Harness the power of Nginx to make the most of your infrastructure and serve pages faster than ever before, 4th Edition

Rating is 4.7 out of 5

Nginx HTTP Server: Harness the power of Nginx to make the most of your infrastructure and serve pages faster than ever before, 4th Edition

5
NGINX Cookbook: Advanced Recipes for High-Performance Load Balancing

Rating is 4.6 out of 5

NGINX Cookbook: Advanced Recipes for High-Performance Load Balancing

6
Nginx Simplified: Practical Guide to Web Server Configuration and Optimization

Rating is 4.5 out of 5

Nginx Simplified: Practical Guide to Web Server Configuration and Optimization


How do I limit CORS to specific subdomains?

To limit CORS (Cross-Origin Resource Sharing) to specific subdomains, you can configure your server to include the Access-Control-Allow-Origin response header with the allowed subdomains.


Here is a general guideline on how to achieve this for different server-side technologies:

  1. Configuring CORS for Apache (using .htaccess file): Create or edit the .htaccess file in the root directory of your website. Add the following lines to allow CORS for specific subdomains only: Header set Access-Control-Allow-Origin "https://subdomain.example.com" Replace https://subdomain.example.com with the specific subdomain you want to allow.
  2. Configuring CORS for Nginx: Open your Nginx server configuration file (usually located at /etc/nginx/nginx.conf or /etc/nginx/sites-available/default). Inside the server block or location block if CORS is needed for specific endpoints, add the following lines: location / { add_header Access-Control-Allow-Origin https://subdomain.example.com; } Again, replace https://subdomain.example.com with the subdomain you want to allow.
  3. Configuring CORS for Node.js (Express.js framework): Install the cors package by running npm install cors --save. In your Express.js application file, import the package and use it as middleware: const express = require('express'); const cors = require('cors'); const app = express(); const allowedOrigins = ['https://subdomain.example.com']; const corsOptions = { origin: function (origin, callback) { if (allowedOrigins.indexOf(origin) !== -1 || !origin) { callback(null, true); } else { callback(new Error('Not allowed by CORS')); } } }; app.use(cors(corsOptions)); // ... other middleware and routes app.listen(3000, () => { console.log('Server is running on port 3000'); }); Modify the allowedOrigins array to include the specific subdomains you want to allow.


Remember to adjust the code provided according to your specific server and subdomain configurations. Additionally, you may need to restart your server for the changes to take effect.


How do I configure NGINX to handle CORS preflight requests?

To configure NGINX to handle CORS preflight requests, you need to add the necessary headers to the server configuration. Follow the steps below:

  1. Open the NGINX configuration file for your website. This file is usually located at /etc/nginx/nginx.conf or /etc/nginx/conf.d/default.conf.
  2. Locate the server block that corresponds to your website or create a new one if it doesn't exist. It should look something like this:
1
2
3
4
5
server {
    listen 80;
    server_name example.com;
    ...
}


  1. Inside the server block, add the following lines to enable the necessary headers for CORS preflight requests:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
location / {
    if ($request_method = 'OPTIONS') {
        add_header 'Access-Control-Allow-Origin' '*';
        add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS';
        add_header 'Access-Control-Allow-Headers' 'DNT,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Range';
        add_header 'Access-Control-Max-Age' 1728000;
        add_header 'Content-Type' 'text/plain; charset=utf-8';
        add_header 'Content-Length' 0;
        return 204;
    }

    ...
}


  1. Save the configuration file and restart NGINX to apply the changes. The command to restart NGINX varies depending on your operating system. Here are a few examples:
  • Ubuntu: sudo service nginx restart
  • CentOS: sudo systemctl restart nginx
  • macOS: sudo nginx -s reload


With these configurations, NGINX will respond to preflight requests (OPTIONS method) with the appropriate CORS headers. Make sure to adjust the Access-Control-Allow-Origin header to match your desired origin restrictions.


Is there a performance impact of enabling CORS in NGINX?

Enabling CORS (Cross-Origin Resource Sharing) in NGINX can have a performance impact, but it is typically negligible. When a browser makes a cross-origin request, and the server has CORS enabled, additional headers are included in the response to indicate that the resource can be accessed from a different origin. These headers add a small overhead to the response size.


However, the impact on performance depends on several factors, such as the number of CORS requests made to the server and the size of the response. In most cases, the impact is minimal and does not significantly degrade performance.


If you are concerned about the performance impact of enabling CORS, you can consider implementing caching mechanisms, such as setting appropriate cache headers, to reduce the number of CORS requests and improve overall performance.

Best Web Hosting Providers of October 2024

1
Vultr

Rating is 5 out of 5

Vultr

  • Ultra-fast Intel Core Processors
  • Great Uptime and Support
  • High Performance and Cheap Cloud Dedicated Servers
2
Digital Ocean

Rating is 4.9 out of 5

Digital Ocean

  • Professional hosting starting at $5 per month
  • Remarkable Performance


Is it possible to enable CORS for a single domain?

Yes, it is possible to enable Cross-Origin Resource Sharing (CORS) for a single domain. CORS is primarily a server-side configuration, and you can configure your server to allow requests from specific domains while blocking requests from others.


To enable CORS for a single domain, you need to configure your server to include the appropriate CORS headers in the response. This typically includes adding the "Access-Control-Allow-Origin" header with the value of the allowed domain. For example:

1
Access-Control-Allow-Origin: https://example.com


By setting this header, the server allows requests coming from the specified domain. Any requests originating from other domains will be blocked, as per the default CORS behavior.


It's important to note that the specific implementation and configuration may vary depending on the server technology you are using.


How can I specify multiple allowed origins?

To specify multiple allowed origins, you can pass an array of origin URLs to the Access-Control-Allow-Origin header on the server-side. Here's an example of how you can do it using different programming languages:


In PHP:

1
2
3
4
5
6
7
8
9
$allowedOrigins = array(
    'http://example1.com',
    'http://example2.com',
    'http://example3.com'
);

if (in_array($_SERVER['HTTP_ORIGIN'], $allowedOrigins)) {
    header('Access-Control-Allow-Origin: ' . $_SERVER['HTTP_ORIGIN']);
}


In Node.js (with Express.js):

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
const express = require('express');
const app = express();

const allowedOrigins = [
    'http://example1.com',
    'http://example2.com',
    'http://example3.com'
];

app.use((req, res, next) => {
    const origin = req.headers.origin;
    if (allowedOrigins.includes(origin)) {
        res.setHeader('Access-Control-Allow-Origin', origin);
    }
    // Rest of your code
});


In Python (with Flask):

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
from flask import Flask, request

app = Flask(__name__)

allowed_origins = [
    'http://example1.com',
    'http://example2.com',
    'http://example3.com'
]

@app.after_request
def add_cors_headers(response):
    origin = request.headers.get('Origin')
    if origin in allowed_origins:
        response.headers.add('Access-Control-Allow-Origin', origin)
    return response

# Rest of your code


Remember to replace the example URLs with your actual allowed origins. By allowing multiple origins, the server will respond with the appropriate Access-Control-Allow-Origin header, allowing requests from any of the specified origins.

Facebook Twitter LinkedIn Telegram Whatsapp Pocket

Related Posts:

To use NGINX to host a website, follow these steps:Install NGINX: Begin by installing NGINX on your server or computer. The installation process may vary depending on your operating system. NGINX has official documentation to guide you through the installation...
To enable Brotli compression in NGINX, you can follow these steps:Start by installing the necessary tools. Ensure that you have the NGINX web server installed on your system. You also need the Brotli compression library and the ngx_brotli module for NGINX. Onc...
To install Nginx in Arch Linux, you can follow these steps:Update the package manager by running the command: sudo pacman -Syu Install Nginx by executing the command: sudo pacman -S nginx Once the installation is complete, start the Nginx service using: sudo s...
To enable keepalive in NGINX, you need to make some changes in the NGINX configuration file. Here are the steps:Open the NGINX configuration file in a text editor. The location of the file varies depending on your operating system and NGINX installation, but c...
To configure Nginx in Ubuntu, you need to perform the following steps:Install Nginx: Begin by installing Nginx using the package manager of Ubuntu. Enter the command sudo apt-get install nginx in the terminal to perform the installation. Start Nginx: After the...
To increase the NGINX timeout, you need to make changes to the NGINX configuration file. Here's how:Locate the NGINX configuration file. It is typically named nginx.conf or nginx.conf.sample and is usually located in the /etc/nginx/ directory. Open the NGI...