Nginx配置WildFly应用:将/myapp/路径改为根域名访问
Hey there! Since you're new to Nginx, let's walk through this configuration change step by step—it's simpler than it sounds.
First, Understand Your Current Setup
Chances are your existing Nginx config has a location block targeting /myapp/ to proxy requests to WildFly. It might look something like this:
server { listen 80; server_name myapp.site.com; location /myapp/ { proxy_pass http://your-wildfly-server:8080/myapp/; # Common proxy headers (you probably have these too) proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; } }
Modify the Config to Use the Root Domain
We need to adjust the location block to target the root path (/) instead of /myapp/, and make sure requests get forwarded to the correct context path on WildFly. You have two reliable ways to do this:
Method 1: Use Rewrite to Prefix Requests
This rewrites every incoming request to add the /myapp/ prefix before sending it to WildFly:
server { listen 80; server_name myapp.site.com; location / { # Rewrite the path: e.g., /test becomes /myapp/test rewrite ^/(.*)$ /myapp/$1 break; proxy_pass http://your-wildfly-server:8080; # Keep your existing proxy headers (critical for WildFly to know client details) 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; # Add this if using HTTPS later } }
Method 2: Directly Proxy to the WildFly Context Path
If your WildFly app is deployed under the /myapp/ context, you can skip the rewrite and point proxy_pass directly to that path. Just make sure to include the trailing slash:
server { listen 80; server_name myapp.site.com; location / { proxy_pass http://your-wildfly-server:8080/myapp/; # Same proxy headers as above 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; } }
This works because Nginx will append the incoming request path to the end of the proxy_pass URL. So myapp.site.com/test gets sent to http://your-wildfly-server:8080/myapp/test.
Test and Apply the Changes
- Check for config errors: Run
sudo nginx -tin your terminal. If you see "test is successful", you're good to go. - Reload Nginx: Apply the changes with
sudo systemctl reload nginx(orsudo service nginx reloaddepending on your OS).
That's it! Now visiting myapp.site.com should load your WildFly app directly, no /myapp/ path needed.
内容的提问来源于stack exchange,提问作者BzVs

