📜  nginx enable cors (1)

📅  最后修改于: 2023-12-03 15:33:06.903000             🧑  作者: Mango

Nginx Enable CORS

CORS (Cross-Origin Resource Sharing) is a mechanism that allows web browsers to make cross-domain HTTP requests. By default, web browsers enforce the same-origin policy which restricts web pages from making requests to a different domain than the one the page was served from. CORS provides a method for relaxing this restriction.

Nginx is a popular web server that can be used to enable CORS for a web application. In this guide, we will show you how to enable CORS for an Nginx web server.

Step 1: Install Nginx

If you haven't already, you will need to install Nginx on your server. You can do this by running the following command:

sudo apt-get update
sudo apt-get install nginx
Step 2: Create an Nginx Configuration File

Next, you need to create an Nginx configuration file. We will assume that you want to enable CORS for a specific domain, so we will create a configuration file for that domain.

Create a new file called yourdomain.com.conf in the sites-available directory:

sudo nano /etc/nginx/sites-available/yourdomain.com.conf

Add the following configuration to the file. Replace yourdomain.com with your actual domain name:

server {
    listen 80;
    server_name yourdomain.com;

    location / {
        add_header 'Access-Control-Allow-Origin' '*' always;
        add_header 'Access-Control-Allow-Methods' 'GET, POST, PUT, DELETE, OPTIONS' always;
        add_header 'Access-Control-Allow-Headers' 'DNT,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Range' always;
        add_header 'Access-Control-Expose-Headers' 'Content-Length,Content-Range' always;
        if ($request_method = 'OPTIONS') {
            add_header 'Access-Control-Allow-Origin' '*' always;
            add_header 'Access-Control-Allow-Methods' 'GET, POST, PUT, DELETE, OPTIONS' always;
            add_header 'Access-Control-Allow-Headers' 'DNT,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Range' always;
            add_header 'Access-Control-Max-Age' 1728000;
            add_header 'Content-Type' 'text/plain charset=UTF-8';
            add_header 'Content-Length' 0;
            return 204;
        }
    }
}

Save and close the file.

Step 3: Enable the Configuration File

Create a symbolic link to the configuration file in the sites-enabled directory:

sudo ln -s /etc/nginx/sites-available/yourdomain.com.conf /etc/nginx/sites-enabled/

Test the configuration for syntax errors:

sudo nginx -t

If there are no errors, reload Nginx to apply the changes:

sudo service nginx reload
Conclusion

In this guide, we showed you how to enable CORS for an Nginx web server. By setting the Access-Control-Allow-Origin header to *, you allow any origin to make cross-domain requests to your web server. You can customize the headers to allow specific HTTP methods, headers, and expose headers.