how is nginx configured in a web app

tags: learning networking programming

content

  • in the below nginx config, is the section location /api/ needed if backend service is not directly accessible from public internet?
    • let’s learn about what it does with some comments
server {
    listen 80;
	# `_` is a catch-all
	# requests to all domain is accepted and proccesd
    server_name _;
	# `/usr/share/nginx/html` is where the frontend static files (js, html, css, etc) are
	# in frontend dockerfile the static files are built and copied to this location
    root /usr/share/nginx/html;
    index index.html;
 
	# traffic to `/api/` (url contains `/api/`) is processed with following rules
    location /api/ {
		# forward `/api/` traffic to this url 
		# `backend` is the service name defined in docker compose
		# `backend` is how the nginx service can reach the backend container
        proxy_pass http://backend:8080;
		# with the following headers
        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;
    }
    # SPA fallback
	# other traffic is handled here
    location / {
        try_files $uri $uri/ /index.html;
    }
}
  • nginx is doing two things here:

    • serving static files (js, css, html, etc) built by vite or other build tools
    • routing traffic (url with /api/) to another url
  • when frontend and backend are behind the same domain, this nginx is necessary!

    • i.e., when requests for static files and backend api requests are both mydomain.com
      • frontend: mydomain.com/coffees
      • backend mydomain.com/api/v1/coffees/new
    • even when backend is not exposed to the public internet
  • nginx also helps with CORS-what-is-it

up

down

reference