Laravel 5.8 .htaccess添加特定重定向及404跳转方法咨询
Hey there! Let's get those redirects sorted for your Laravel 5.8 site. Since your existing .htaccess is working fine, we just need to add a few targeted rules in the right place. Here's exactly what to do:
Step 1: Locate your .htaccess file
It should be in the public directory of your Laravel project (this is the web root your server points to). Open it up in your favorite text editor.
Step 2: Add custom redirect rules
Insert these rules right after the RewriteEngine On line (before the existing Laravel rules like handling authorization or trailing slashes). This ensures our specific redirects get processed first:
# Redirect specific 404 paths to their new URLs RewriteCond %{REQUEST_FILENAME} !-d RewriteCond %{REQUEST_FILENAME} !-f RewriteRule ^oferta$ https://domain.pl/oferta-2020 [L,R=301] RewriteCond %{REQUEST_FILENAME} !-d RewriteCond %{REQUEST_FILENAME} !-f RewriteRule ^kontakt$ https://domain.pl/contact [L,R=301] # Redirect all other 404s to the homepage RewriteCond %{REQUEST_FILENAME} !-d RewriteCond %{REQUEST_FILENAME} !-f RewriteRule ^ https://domain.pl/ [L,R=301]
Let me break down what each part does:
RewriteCond %{REQUEST_FILENAME} !-dandRewriteCond %{REQUEST_FILENAME} !-f: These check that the requested path isn't an existing directory or file (so we only redirect actual 404s, not valid pages/files).RewriteRule ^oferta$ ...: Matches exactly the/ofertapath and redirects it to your new URL. The^and$ensure we don't match paths like/oferta/something-else.[L,R=301]:Ltells Apache to stop processing further rules once this one runs;R=301is a permanent redirect, which is good for SEO (search engines will update their indexes to the new URL).
Quick tips:
- Replace
domain.plwith your actual domain name everywhere in the rules. - If you want to test first (before making permanent changes), use
R=302instead of301(this is a temporary redirect). Once you confirm everything works, switch back to301. - These rules won't interfere with your existing Laravel routes—since we're checking for non-existent files/directories, valid routes handled by Laravel's
index.phpwill still work as normal.
Final check
Save the .htaccess file, then test the URLs:
- Visit
https://domain.pl/oferta—it should redirect to/oferta-2020 - Visit
https://domain.pl/kontakt—it should redirect to/contact - Visit any other non-existent path (like
/random-page)—it should redirect to the homepage
That should cover all your requirements! 😊
内容的提问来源于stack exchange,提问作者opolopo
相关产品推荐
相关产品推荐

