【问题标题】:htaccess - remove index.php and keep a variable without keyhtaccess - 删除 index.php 并保留一个没有键的变量
【发布时间】:2021-06-30 16:42:21
【问题描述】:

原始网址是以下之一:

  • example.com
  • example.com/index.php
  • example.com/index.php?c=lorem

如果example.com - 什么都不应该做
如果example.com/index.php - 它应该以example.com 可见,这是我的代码 - 工作正常:

RewriteEngine ON
RewriteRule ^index\.php/?$ https://%{HTTP_HOST}/ [NC,R=301]
RewriteRule ^/?$ index.php [L]

如果example.com/index.php?c=lorem 它应该显示为example.com/lorem

lorem 在这两种情况下都应该可以被php访问:

  • 如果用户键入example.com/index.php?c=lorem
  • 用户类型example.com/lorem

请帮忙

【问题讨论】:

    标签: apache .htaccess mod-rewrite url-rewriting friendly-url


    【解决方案1】:

    您可以在站点根目录 .htaccess 中使用这些规则:

    DirectoryIndex index.php
    RewriteEngine On
    
    # remove index.php
    RewriteCond %{THE_REQUEST} /index\.php\s [NC]
    RewriteCond %{REQUEST_URI} ^(.*/)index\.php$ [NC]
    RewriteRule ^ %1 [L,R=301,NE]
    
    # external redirect from actual URL to pretty one
    RewriteCond %{THE_REQUEST} \s/+index\.php\?c=([^\s&]+) [NC]
    RewriteRule ^ /%1? [R=301,L,NE]
    
    # internal forward from pretty URL to actual one
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteRule ^([^/.]+)/?$ index.php?c=$1 [L,QSA]
    

    【讨论】:

      【解决方案2】:

      请根据您显示的示例尝试以下操作。 请在测试您的 URL 之前清除您的浏览器缓存。

      RewriteEngine ON
      ##This rule is for handling index.php file in uri.
      RewriteCond %{QUERY_STRING} ^$
      RewriteRule ^index\.php/?$ / [R=301,NC,L]
         
      ##This rule is to redirect from index.php?c=lorem to lorem in uri.
      RewriteCond %{THE_REQUEST} index\.php\?c=(lorem)\s [NC]
      RewriteRule ^ http://%{HTTP_HOST}/%1? [R=301,L,NE]
      
      ##Rule for non-existing files/directories to index.php with variables.
      RewriteCond  %{REQUEST_FILENAME} !-f
      RewriteCond  %{REQUEST_FILENAME} !-d
      RewriteRule ^(.*)$ index.php?c=$1 [L]
      


      或者:以上是专门针对lorem的,以防您的查询字符串可以是任何内容,然后尝试关注。

      RewriteEngine ON
      ##This rule is for handling index.php file in uri.
      RewriteCond %{QUERY_STRING} ^$
      RewriteRule ^index\.php/?$ / [R=301,NC,L]
         
      ##This rule is to redirect from index.php?c=lorem to lorem in uri.
      RewriteCond %{THE_REQUEST} index\.php\?c=([^\s&]*) [NC]
      RewriteRule ^ http://%{HTTP_HOST}/%1? [R=301,L,NE]
      
      ##Rule for non-existing files/directories to index.php with variables.
      RewriteCond  %{REQUEST_FILENAME} !-f
      RewriteCond  %{REQUEST_FILENAME} !-d
      RewriteRule ^(.*)$ index.php?c=$1 [L]
      

      【讨论】:

      • 您的代码也有效。我接受 Anubhava 的只是因为他是第一个——在没有其他正确标准的情况下。我希望没关系
      猜你喜欢
      • 2021-07-11
      • 1970-01-01
      • 2016-03-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多