在FastAdmin开发中,可能会遇到需要将包含 index.php
的URL重定向到不包含 index.php
的URL的情况。这是为了避免SEO问题,因为相同内容的不同URL会影响搜索引擎优化。以下是实现301重定向的方法:
Apache 实现方法
打开并编辑
public/.htaccess
文件,在RewriteEngine On
后添加以下代码:# Redirect if index.php is in the URL RewriteCond %{THE_REQUEST} /index\.php [NC] RewriteCond %{REQUEST_FILENAME} -f RewriteRule ^index\.php([\/\?]?)(.*)$ /$2 [R=301,L]
最终
.htaccess
文件内容 应如下所示:<IfModule mod_rewrite.c> Options +FollowSymlinks -Multiviews RewriteEngine On # Redirect if index.php is in the URL RewriteCond %{THE_REQUEST} /index\.php [NC] RewriteCond %{REQUEST_FILENAME} -f RewriteRule ^index\.php([\/\?]?)(.*)$ /$2 [R=301,L] RewriteCond %{REQUEST_FILENAME} !-d RewriteCond %{REQUEST_FILENAME} !-f RewriteRule ^(.*)$ index.php/$1 [QSA,PT,L] </IfModule>
Nginx 实现方法
找到 Nginx 站点的配置文件,在
location / {}
配置之前添加以下代码:# Remove index.php$ if ($request_uri ~* "^(.*/)index\.php$") { return 301 $1; } # Remove index.php from everywhere if ($request_uri ~* "^(.*/)index\.php(/?)(.*)") { return 301 $1$3; }
温馨提示
- 测试环境: 以上方法在 Apache 2.4.25 和 Nginx 1.18.0 版本中测试通过。由于 Apache 和 Nginx 的版本众多,请务必在开发环境中进行充分测试后,再同步到生产环境。