关键词搜索

全站搜索
×
密码登录在这里
×
注册会员

已有账号? 请点击

忘记密码

已有账号? 请点击

使用其他方式登录

thinkphp伪静态隐藏index.php并301跳转

发布2023-09-22 浏览414次

详情内容

在用thinkphp开发网站时,因为是单入口文件,为了SEO或url短些需要用到隐藏index.php,在thinkphp官方给种的伪静态可隐藏index.php,但是有个问题,手动在url加index.php还是可以访问,url中还是有index.php。

看官方给的伪静态:

[ Apache ]

httpd.conf配置文件中加载了mod_rewrite.so模块

AllowOverride None 将None改为 All

把下面的内容保存为.htaccess文件放到应用入口文件的同级目录下

<IfModule mod_rewrite.c>
  Options +FollowSymlinks -Multiviews
  RewriteEngine On
  RewriteCond %{REQUEST_FILENAME} !-d
  RewriteCond %{REQUEST_FILENAME} !-f
  RewriteRule ^(.*)$ index.php/$1 [QSA,PT,L]</IfModule>

[ IIS ]

如果你的服务器环境支持ISAPI_Rewrite的话,可以配置httpd.ini文件,添加下面的内容:

RewriteRule (.*)$ /index\.php\?s=$1 [I]

在IIS的高版本下面可以配置web.Config,在中间添加rewrite节点:

<rewrite>
 <rules>
 <rule name="OrgPage" stopProcessing="true">
 <match url="^(.*)$" />
 <conditions logicalGrouping="MatchAll">
 <add input="{HTTP_HOST}" pattern="^(.*)$" />
 <add input="{REQUEST_FILENAME}" matchType="IsFile" negate="true" />
 <add input="{REQUEST_FILENAME}" matchType="IsDirectory" negate="true" />
 </conditions>
 <action type="Rewrite" url="index.php/{R:1}" />
 </rule>
 </rules>
 </rewrite>

[ Nginx ]

在Nginx低版本中,是不支持PATHINFO的,但是可以通过在Nginx.conf中配置转发规则实现:

location / { // …..省略部分代码
   if (!-e $request_filename) {
   rewrite  ^(.*)$  /index.php?s=/$1  last;
    }}

问题来了,如手动浏览器输入:https://www.uihtm.com/index.php/shangcheng/ 还是没跳转,这样会导致,

https://www.uihtm.com/index.php/shangcheng/

https://www.uihtm.com/shangcheng/

这2个url内容一样,不利于SEO也不美观,最好的办法是让带有index.php入口的url自动301跳转到后删除index.php。

方法如下:

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 / {}配置之前添加以下代码即可

# 删除 index.php$
if ($request_uri ~* "^(.*/)index\.php$") {
   return 301 $1;
}

# 删除 from everywhere index.php
if ($request_uri ~* "^(.*/)index\.php(/?)(.*)") {
   return 301 $1$3;
}

location / {
    index  index.php index.html index.htm;
    #如果请求既不是一个文件,也不是一个目录,则执行一下重写规则
    if (!-e $request_filename)
     {
        #地址作为将参数rewrite到index.php上。
        rewrite ^/(.*)$ /index.php?s=$1;
        #若是子目录则使用下面这句,将subdir改成目录名称即可。
        #rewrite ^/subdir/(.*)$ /subdir/index.php?s=$1;
     }
}


点击QQ咨询
开通会员
上传资源赚钱
返回顶部
×
  • 微信支付
  • 支付宝付款
扫码支付
微信扫码支付
请使用微信描二维码支付
×

提示信息

×

选择支付方式

  • 微信支付
  • 支付宝付款
确定支付下载