【问题标题】:How to remove index.php and hide parameter lang from url?如何从 url 中删除 index.php 并隐藏参数 lang?
【发布时间】:2019-09-13 11:32:31
【问题描述】:

我有以下网址

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

【问题讨论】:

  • 您能告诉我们您是如何编写重写条件规则的吗?
  • @catcon 请检查我的问题,我已经添加了我的 htaccess 规则。
  • 当我尝试这个 url localhost/apps/site/es 直接将我重定向到 127.0.0.1/dashboard 时,为什么我觉得你在其他地方有另一个重写,它在你之前运行..跨度>

标签: php .htaccess mod-rewrite url-rewriting


【解决方案1】:
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(您必须在 L flag 之前设置它,这将 不 工作@987654334 @)

现在,如果您要求

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

会改写成

http://localhost/apps/site/es

你可以在这个网站https://htaccess.madewithlove.be/上测试和玩重写规则

【讨论】:

  • 感谢您的回答,但此解决方案不适用于我。
  • 当您请求http://localhost/apps/site/index.php?lang=es 时,会重写哪个 URL?
  • 没什么,还是一样的 url (localhost/apps/site/index.php?lang=es)
  • 我已经尝试过这个解决方案并且它的工作:RewriteEngine On RewriteCond %{HTTP_HOST} ^127.0.0.1/apps/site RewriteRule (.*) 127.0.0.1/apps/site/$1 [R=301,L] RewriteEngine On RewriteCond %{HTTP:X-Forwarded-Proto} !https RewriteCond %{QUERY_STRING} !.*healthCheck=true.* RewriteRule ^([a-zA-Z0-9_-]+)$ index.php?lang=$1 RewriteRule ^ ([a-zA-Z0-9_-]+)/$ index.php?lang=$1
  • 它是否将这个http://localhost/apps/site/index.php?lang=es重写为这个http://localhost/apps/site/es?
猜你喜欢
  • 2015-07-21
  • 2014-03-13
  • 2011-02-15
  • 2015-12-19
  • 2012-05-15
  • 1970-01-01
相关资源
最近更新 更多