代码之家  ›  专栏  ›  技术社区  ›  Chris

.htaccess重写规则以不包含index.php

  •  2
  • Chris  · 技术社区  · 8 年前

    我有一个.htaccess规则,它获取url的第一个目录部分,并使用它从数据库中查找产品,如下所示www.website.com/product-1。我使用下面的规则,它运行良好:

    RewriteRule ^([-_a-z0-9]+)?$ /product.php?product_url=$1 [NC,L]

    问题是,当我访问主页www.website.com/时,它试图寻找一个空白产品。如果我想访问主页,我必须使用www.website.com/index.php。

    如何保持上面的url结构,但使www.website.com/显示主页index.php?

    3 回复  |  直到 8 年前
        1
  •  2
  •   Mr Glass    8 年前

    这将跳过index.php

    RewriteRule ^index\.php$ - [L]
    RewriteRule ^([-_a-z0-9]+)?$   /product.php?product_url=$1    [NC,L]
    
        2
  •  3
  •   anubhava    8 年前

    主要问题是正则表达式也匹配空字符串。

    您应该改为使用此规则:

    RewriteRule ^([-_a-z0-9]+)/?$ product.php?product_url=$1 [NC,L,QSA]
    

    另外,请考虑使用这两个条件跳过此重写中的所有文件和目录:

    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteRule ^([-_a-z0-9]+)/?$ product.php?product_url=$1 [NC,L,QSA]
    
        3
  •  1
  •   Shasha    8 年前

    你可以试试这个:也可以检查并修改我曾经问过的这个问题,看看你是否可以调整它 Perform If statements for a specific file name in .htaccess

    RewriteRule ^index\.php$ - [L] //This would make it skip index.php and look at product.php
    RewriteRule ^([-_a-z0-9]+)?$   /product.php?product_url=$1    [NC,L]