skip to Main Content

I have configured the NGINX server configuration for the location of the application but I am getting the index.html data with 200 status instead of the original API response.

API response:
enter image description here

enter image description here

The server configuration on the NGINX side is as follows:

server {
    listen 443 default_server;
    listen [::]:443 default_server;
    ssl on;

    server_name abc.global;
    root /var/www/html/build;

    location / {
            try_files $uri $uri/ /index.html;
    }

    location = /50x.html {
            alias /var/www/html/build;
    }

    error_page  404     /404.html;
    error_page  403     /403.html;

    # To allow POST on static pages
    error_page  405     =200 $uri;

    ssl_certificate /Path/abc.crt;
    ssl_certificate_key /Path/abc.key;

Can anyone please guide me, Whats the issue in the server configuration that I am getting this issue?

2

Answers


  1. proxy_pass

    An api needs a different settings compared with static web. You need to use proxy_pass. Check:

    tips

    Login or Signup to reply.
  2. change your NGINX config to following:

    server {
        listen 443 default_server;
        listen [::]:443 default_server;
        ssl on;
    
        server_name abc.global;
        root /var/www/html/build;
    
        # Handle API requests separately
        location /api/ {
            proxy_pass http://localhost:3000;  # Adjust this to your API server's address and port
            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;
        }
    
        # Serve static files and fallback to index.html for single-page apps
        location / {
            try_files $uri $uri/ /index.html;
        }
    
        location = /50x.html {
            alias /var/www/html/build;
        }
    
        error_page  404     /404.html;
        error_page  403     /403.html;
    
        # To allow POST on static pages
        error_page  405     =200 $uri;
    
        ssl_certificate /Path/abc.crt;
        ssl_certificate_key /Path/abc.key;
    }
    

    explanation:

    1. The location /api/ block is designed to forward any API requests (e.g., /api/users) to your backend API server running on http://localhost:3000 (you can change this based on where your API is hosted).
    2. The location / block will continue serving static files (like index.html) for non-API requests, making it suitable for single-page applications (SPAs).
    3. Ensure that your API path correctly starts with /api/ or adjust the location block accordingly.If your API path is different (e.g., /v1/api or something else), you will need to adjust the location directive to match your API routes.
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search