Symfony 4公共目录图片触发NotFoundHttpException:路由缺失致图片无法显示
Let’s walk through exactly why you’re hitting this NotFoundHttpException and how to fix it—this is a super common static asset issue in Symfony, so you’re not alone!
Step 1: Verify your image’s location
Symfony serves all static assets (images, CSS, JS) exclusively from the public/ directory at your project root. Double-check that:
- You have a
public/image/folder (create it if it doesn’t exist) - Your
seta.pngfile is directly insidepublic/image/
If the file lives somewhere else (like src/Resources/ or the project root), Symfony’s web server won’t be able to access it directly.
Step 2: Use the asset() function in your templates
Never hardcode asset paths in Twig—use Symfony’s built-in asset() helper to generate the correct URL. This avoids path mistakes and ensures compatibility with environment-specific setups (like asset versioning in production).
Replace any hardcoded image tags like this:
<img src="/image/seta.png" alt="Seta">
With this Twig code:
<img src="{{ asset('image/seta.png') }}" alt="Seta">
Step 3: Check your server configuration
If you’re using the Symfony built-in server (started with symfony server:start or php -S localhost:8000 -t public), it should handle static assets automatically. But if you’re using Apache or Nginx:
- Apache: Make sure your virtual host’s
DocumentRootpoints to thepublic/folder, not the project root. Example:DocumentRoot "/var/www/your-project/public" <Directory "/var/www/your-project/public"> AllowOverride All Require all granted </Directory> - Nginx: Ensure your server block sets
rootto thepublic/directory:server { root /var/www/your-project/public; index index.php index.html; location / { try_files $uri $uri/ /index.php$is_args$args; } }
If your server points to the project root instead of public/, it’ll look for image/seta.png in the root (which doesn’t exist) and pass the request to Symfony’s router—causing the "No route found" error.
Step 4: Clear your Symfony cache
Stale cache can cause unexpected asset glitches, especially in development. Run this command in your project root:
php bin/console cache:clear
Then restart your server to ensure changes take effect.
Step 5: Check permissions and custom routes
- Permissions: Ensure
public/image/seta.pnghas readable permissions (usually644) and thepublic/image/folder has755permissions. The web server needs to read the file. - Custom Routes: If you’ve defined routes matching patterns like
/image/{file}, they might intercept the static asset request. Double-check yourconfig/routes.yaml(or annotation routes) to make sure these aren’t overriding static asset handling.
Test directly
After making these changes, try accessing http://localhost:8000/image/seta.png directly in your browser. If the image loads, your template should display it correctly too.
内容的提问来源于stack exchange,提问作者Ronald2g

