请求配置Apache实现同域名下静态SPA、WordPress及Node.js API部署
Got it, let's get your Apache server set up to host all three services under mydomain.com exactly as you need. Here's a complete, step-by-step solution:
Prerequisites
First, make sure you've enabled the necessary Apache modules—these are required for rewrite rules, aliases, and reverse proxying:
sudo a2enmod rewrite proxy proxy_http sudo systemctl restart apache2
Virtual Host Configuration
Create or edit your domain's virtual host file (e.g., /etc/apache2/sites-available/mydomain.conf):
<VirtualHost *:80> ServerName mydomain.com ServerAlias www.mydomain.com # 1. Static React SPA at root (/) DocumentRoot /var/www/html/ui <Directory /var/www/html/ui> Options -Indexes +FollowSymLinks AllowOverride All Require all granted # Handle SPA routing (fixes 404 on page refresh) RewriteEngine On RewriteBase / RewriteRule ^index\.html$ - [L] RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule . /index.html [L] </Directory> # 2. WordPress at /admin Alias /admin /var/www/wordpress/Commdev <Directory /var/www/wordpress/Commdev> Options -Indexes +FollowSymLinks AllowOverride All Require all granted # WordPress rewrite rules for permalinks RewriteEngine On RewriteBase /admin/ RewriteRule ^index\.php$ - [L] RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule . /admin/index.php [L] </Directory> # 3. Node.js API at /api (proxies to localhost:3000/api) ProxyPass /api http://localhost:3000/api ProxyPassReverse /api http://localhost:3000/api ErrorLog ${APACHE_LOG_DIR}/mydomain-error.log CustomLog ${APACHE_LOG_DIR}/mydomain-access.log combined </VirtualHost>
Post-Configuration Steps
Fix Directory Permissions
Ensure Apache's user (www-data) has access to your application directories:sudo chown -R www-data:www-data /var/www/html/ui /var/www/wordpress/Commdev sudo chmod -R 755 /var/www/html/ui /var/www/wordpress/CommdevUpdate WordPress Settings
Log into your WordPress admin atmydomain.com/admin/wp-admin, then go to Settings > General:- Set "WordPress Address (URL)" to
https://mydomain.com/admin(use HTTPS if you enable SSL later) - Set "Site Address (URL)" to
https://mydomain.com/admin
Save changes to ensure WordPress generates correct links.
- Set "WordPress Address (URL)" to
Test & Activate
- Validate your Apache configuration:
sudo apache2ctl configtest - Enable the virtual host and restart Apache:
sudo a2ensite mydomain.conf sudo systemctl restart apache2
- Validate your Apache configuration:
Optional: HTTPS Setup
If you want to use HTTPS (highly recommended), use Let's Encrypt to get a free SSL certificate:
sudo apt install certbot python3-certbot-apache sudo certbot --apache -d mydomain.com -d www.mydomain.com
Certbot will automatically update your virtual host config to use HTTPS.
内容的提问来源于stack exchange,提问作者Daniele Salvatore

