If you're running a website or an API, chances are you'll need to deal with domains, subdomains, and that ever-annoying CORS issue. Let’s break it down step by step and get everything set up smoothly.

Setting Up Domains and Subdomains in Nginx

Nginx makes it super easy to configure multiple domains and subdomains. You just need to set up server blocks (aka virtual hosts) to tell Nginx which domain should point where.

Using Nginx as a Reverse Proxy

In this case, we are using Nginx as a reverse proxy. This means that Nginx will receive incoming requests and forward them to the appropriate backend servers based on the subdomain. This setup is useful for load balancing, security, and centralizing request handling.

Redirect HTTP to HTTPS

To ensure all traffic is securely routed through HTTPS, set up a redirect from port 80 to 443:

server {
    listen 80;
    server_name example.com *.example.com;
    return 301 https://$host$request_uri;
}

Handling a Domain and Multiple Subdomains with Dynamic Proxy Pass

If you want to handle both the main domain (example.com) and multiple subdomains (api.example.comblog.example.com, etc.) dynamically, you can extract the subdomain and proxy requests accordingly:

server {
    listen 443 ssl;
    server_name *.example.com;

    ssl_certificate /etc/nginx/ssl/example.com.crt;
    ssl_certificate_key /etc/nginx/ssl/example.com.key;

    set $subdomain "default";
    if ($host ~* ^(.+?)\.example\.com$) {
        set $subdomain $1;
    }

    location / {
        proxy_pass http://backend.$subdomain.example.com;
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto $scheme;
        proxy_set_header Connection "upgrade";
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Authorization $http_authorization;
    }
}

This configuration dynamically extracts the subdomain from the request and proxies the request to a corresponding backend server (backend.<subdomain>.example.com). Additionally, it ensures all necessary headers are forwarded properly.

Now, just enable the configuration and restart Nginx:

sudo ln -s /etc/nginx/sites-available/example.com /etc/nginx/sites-enabled/
sudo nginx -t
sudo systemctl reload nginx

Boom! Your domain and all subdomains should now be working with HTTPS and dynamic proxying.

Dealing with CORS (Cross-Origin Resource Sharing) in Nginx

What’s the Deal with CORS?

CORS is that thing that blocks your frontend from calling an API hosted on another domain. If your frontend lives at app.example.com and your API is at api.example.com, you'll need to allow cross-origin requests.

Enabling CORS in Nginx

To let your API accept requests from another domain, you need to add the right headers in Nginx.

Allow All Origins (Not Always Recommended)

server {
    listen 443 ssl;
    server_name api.example.com;

    ssl_certificate /etc/nginx/ssl/api.example.com.crt;
    ssl_certificate_key /etc/nginx/ssl/api.example.com.key;

    location / {
        add_header 'Access-Control-Allow-Origin' '*';
        add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS';
        add_header 'Access-Control-Allow-Headers' 'Authorization, Content-Type';

        if ($request_method = OPTIONS) {
            return 204;
        }
    }
}

This lets anyone access your API, which is fine for public APIs but risky for private ones.

Allow Only a Specific Domain

Want to limit access to app.example.com? Do this instead:

add_header 'Access-Control-Allow-Origin' 'https://app.example.com';

Handling Preflight Requests

Browsers sometimes send an OPTIONS request before making an actual API call. If you don’t handle it, things will break. Here’s how to allow preflight requests:

location / {
    if ($request_method = OPTIONS) {
        add_header 'Access-Control-Allow-Origin' 'https://app.example.com';
        add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS';
        add_header 'Access-Control-Allow-Headers' 'Authorization, Content-Type';
        return 204;
    }
}

Wrapping Up

Getting domains, subdomains, and CORS right in Nginx isn’t too bad once you know what to tweak. With the right setup, you can avoid headaches and keep your apps running smoothly. Happy coding!