首页 > 解决方案 > 如何从 url 中删除 index.php 并隐藏参数 lang?

问题描述

我有以下网址

http://localhost/apps/site/index.php?lang=es

我想使用 .htaccess 使其如下所示

http://localhost/apps/site/es

.htaccess 规则

<IfModule mod_rewrite.c>

RewriteEngine On
RewriteBase /

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d 
RewriteCond %{REQUEST_FILENAME} !-l
RewriteRule ^(.+?)/?$ /index.php?lang=$1 [L,QSA]

</IfModule>

当我尝试此网址时http://localhost/apps/site/es ,直接将我重定向到http://127.0.0.1/dashboard/

我已经尝试过这个解决方案,但不适用于我:

https://stackoverflow.com/a/30153794/7705186

标签: php.htaccessmod-rewriteurl-rewriting

解决方案


RewriteEngine On
RewriteCond %{REQUEST_URI} ^/apps/site/index.php$
RewriteCond %{QUERY_STRING} ^lang=(\w+)
RewriteRule apps/site/index.php /apps/site/%1 [QSD,L]
  • 第一个条件是告诉模块只有在请求 URI 准确的情况下才应用规则/apps/site/index.php

  • 第二个条件,如果第一个查询参数名称是lang并且它的值是一个单词。()就是捕获参数的值并保存在%1

  • 在规则中,我们告诉模块删除apps/site/index.php并重写它,/apps/site/%1同时替换%1为我们从第二个条件中捕获的值

  • QSDQuery String Discard flag 是让模块不追加查询到最终的url(必须在flag之前设置,L这个不行[L,QSD]

现在,如果您要求

http://localhost/apps/site/index.php?lang=es

它将被重写为

http://localhost/apps/site/es

您可以在此站点https://htaccess.madewithlove.be/上测试和使用重写规则


推荐阅读