To set up a Strapi application under a subfolder (e.g., example.com/subfolder) with Nginx, follow these steps:
1. Strapi Configuration
a. Set Base URL in Strapi
Configure Strapi to recognize the subfolder as its base URL.
-
Environment Variables
Create/update .env in your Strapi project:
STRAPI_URL=http://example.com/subfolder # Full base URL
STRAPI_ADMIN_URL=/subfolder # Admin panel subpath
-
Server Config (Optional)
In config/server.js, explicitly define the URL:
module.exports = ({ env }) => ({
// ...
url: env('STRAPI_URL', 'http://localhost:1337'),
// ...
});
b. Build Strapi Admin
Generate the admin panel files:
npm run build
2. Nginx Configuration
Configure Nginx to route requests to the subfolder and proxy them to Strapi.
Example Nginx Config
server {
listen 80;
server_name example.com;
# Strapi Subfolder Configuration
location /subfolder {
# Rewrite path to remove /subfolder prefix
rewrite ^/subfolder/?(.*)$ /$1 break;
# Proxy to Strapi server
proxy_pass http://localhost:1337;
# Set 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;
# WebSocket support (if needed)
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "upgrade";
}
# Other configurations (e.g., frontend)...
}
Key Directives Explained
rewrite ^/subfolder/?(.*)$ /$1 break:
Strips /subfolder from the URL path before proxying to Strapi.
proxy_pass: Directs traffic to the Strapi server (default port 1337).
- Headers ensure correct client IP and protocol forwarding.
3. Start Strapi and Nginx
-
Run Strapi:
npm run start
Ensure Strapi is bound to 0.0.0.0:1337 (check config/server.js if needed).
-
Reload Nginx:
sudo nginx -t # Test config
sudo systemctl reload nginx
4. Verify Access
- Strapi Admin:
Visit http://example.com/subfolder/admin
- API Endpoints:
Access via http://example.com/subfolder/api/<endpoint>
Troubleshooting
- 403 Forbidden: Ensure Nginx has permissions to access Strapi’s ports.
- Broken Links: Confirm
STRAPI_URL and STRAPI_ADMIN_URL are correctly set.
- CORS Issues: Add CORS middleware to Strapi if the frontend is on a different domain.
This setup ensures Strapi operates entirely under the specified subfolder while leveraging Nginx for efficient routing and security.