How to configure Nginx to serve static files from a CDN or external source?

To configure Nginx to serve static files from a CDN or external source, you can follow these steps:

  1. Open the Nginx configuration file. On most Linux systems, the main configuration file is located at /etc/nginx/nginx.conf.

  2. Inside the http block, create a new server block to handle requests for the specific location where the static files are stored. For example:

    server { listen 80; server_name yourdomain.com; location /static { proxy_pass http://yourcdn.com; proxy_set_header Host yourcdn.com; } }

    In this example, the static files are stored under the /static path on the CDN domain.

  3. Save the configuration file and exit.

  4. Test the Nginx configuration to ensure there are no syntax errors. Run the following command:

    sudo nginx -t
  5. If the test is successful, reload or restart Nginx to apply the changes:

    sudo systemctl reload nginx

    or

    sudo systemctl restart nginx

Now, when a request is made to your Nginx server for a file under the /static location, it will be proxied to your CDN or external source for download.

Note: The specifics of configuring Nginx may vary based on your setup and the CDN provider you are using. Make sure to consult the documentation of your CDN provider for any additional configuration requirements.