Logo Logo

Frontend and backend on the same server

1-Backup current

sudo cp -r /etc/apache2 /etc/apache2_backup
sudo cp -r /var/www /var/www_backup

2-Stop and disable Apache (both use port 80)

sudo systemctl stop apache2
sudo systemctl disable apache2
sudo systemctl status apache2

3-Install Nginx

sudo apt install nginx

4-Copy files to server and enable permissions to www-data group

5- Create /etc/nginx/sites-available/nginxAppConfig

server {
    listen 80;
    server_name barryonweb.com;

    # Proxy settings for Backend API
    location /api/ {
        proxy_pass http://localhost:5000/;
        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 settings for WebSockets
    location /websocket {
        proxy_pass http://localhost:5000/websocket;
        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection "upgrade";
        proxy_set_header Host $host;
    }

    # Serve Frontend React App
    root /var/www/appRootDir/clientDir;
    index index.html;

    location / {
        # Try to serve files directly, fallback to index.html for SPA routing
        try_files $uri /index.html;
    }

    # Logging
    access_log /var/log/nginx/appCfg-access.log;
    error_log /var/log/nginx/appCfg-error.log;
}

6- Create symbolic link to enable configuration:

sudo ln -s /etc/nginx/sites-available/nginxAppConfig  /etc/nginx/sites-enabled/

7-Test the Nginx configuration for syntax errors:

sudo nginx -t

8-Check which user is running (www-data)

cat /etc/nginx/nginx.conf