Symfony生产环境表单提交后路由重定向路径错误求助
Hey there! It sounds like your Symfony app is generating duplicate path segments (mywebsite/public) in production redirects—let's break down the most likely causes and how to fix them.
1. Check Your Web Server's Document Root Configuration
This is the most common culprit. In production, your web server (Apache/Nginx) should point its document root directly to the public folder of your Symfony project, not the parent mywebsite folder.
Example Nginx Config Fix:
If your current config has something like:
server { root /var/www/mywebsite; # Wrong! # ... }
Change it to:
server { root /var/www/mywebsite/public; # Correct! # ... }
Example Apache Config Fix:
Update your VirtualHost to set DocumentRoot to the public folder:
<VirtualHost *:443> DocumentRoot "/var/www/mywebsite/public" ServerName mydomain.fr # ... </VirtualHost>
Also ensure the AllowOverride All directive is set for the public folder so Symfony's .htaccess (if using Apache) works correctly.
2. Correct Symfony's Request Context Base URL
Symfony uses the request context to generate URLs. If your base_url is misconfigured, it'll add extra path segments.
Open config/packages/framework.yaml and check the router settings:
framework: router: request_context: base_url: '/mywebsite' # Only set this if your app is hosted under a subpath (e.g., https://mydomain.fr/mywebsite) # Leave base_url empty if public is directly at the domain root (but in your case, it's under /mywebsite)
If you had base_url: '/mywebsite/public', that's the problem—remove the /public part since the server already serves from public.
3. Always Use Route Names for Redirects
Avoid hardcoding paths in your controllers! Instead of:
// ❌ Bad: Hardcoded path can break with environment changes return $this->redirect('/mywebsite/public/homepage');
Use Symfony's route name generator:
// ✅ Good: Uses the router to generate the correct URL based on context return $this->redirectToRoute('homepage');
This ensures Symfony automatically uses the correct base URL from the request context.
4. Verify Your Production Environment Variables
Check your .env.prod file for the APP_URL setting. It should match the public-facing URL of your app without the /public suffix:
# Correct APP_URL=https://mydomain.fr/mywebsite # Wrong (causes duplication) APP_URL=https://mydomain.fr/mywebsite/public
How to Debug the Context
To confirm what Symfony thinks the base URL is, add this temporary code to your controller:
dump($this->get('router')->getContext()->getBaseUrl()); die;
In production, this will show you the base URL Symfony is using—if it includes /mywebsite/public, that's where the duplication is coming from.
Once you fix the above, your redirect should correctly point to https://mydomain.fr/mywebsite/homepage (the browser will show this, which maps to your public folder under the hood, matching your expected target).
内容的提问来源于stack exchange,提问作者R Lopez

