htaccess for pretty url slugs

时间:2018-02-20 09:28:50

标签: php .htaccess

我正在尝试在项目的根目录中设置一个.htaccess文件,这将使我能够使用漂亮的网址。

我有三种类型的页面:

  1. news.php
  2. tournaments.php
  3. rankings.php
  4. 但是,实际上我需要news.phpview.php,其中后者会处理哪些标记用于锦标赛/排名和新闻报道site-name/news/the-slug-of-the-story/

    这是我到目前为止所做的:

    RewriteEngine On
    RewriteBase /the-site-name/
    RewriteCond %{SCRIPT_FILENAME} !-f
    RewriteCond %{SCRIPT_FILENAME} !-d
    RewriteRule . /news.php [L]
    RewriteRule ^news/(.*)/([0-9]+) news.php?slug=/news/$1 [L]
    RewriteCond %{SCRIPT_FILENAME} !-f
    RewriteCond %{SCRIPT_FILENAME} !-d
    RewriteRule . /view.php [L]
    RewriteRule ^tournaments/(.*)/([0-9]+) view.php?page=/tournaments/$1 [L]
    RewriteCond %{SCRIPT_FILENAME} !-f
    RewriteCond %{SCRIPT_FILENAME} !-d
    RewriteRule . /view.php [L]
    RewriteRule ^rankings/(.*)/([0-9]+) view.php?page=/rankings/$1 [L]
    

    但是,所有链接/锦标赛/ /排名/似乎都在使用news.php模板,而不是view.php。

    我有什么遗失的吗?

    更新时间:20/02/2018 20/02/2018

    我现在正在.htaccess工作 - 这是最终设置

    <IfModule mod_rewrite.c>
    RewriteEngine On
    RewriteCond %{SCRIPT_FILENAME} !-f
    RewriteCond %{SCRIPT_FILENAME} !-d
    RewriteRule ^news/?$ news.php?slug=/news/ [L]
    RewriteRule ^news/(.*)/([0-9]*) news.php?slug=/news/$1/ [L]
    RewriteRule ^rankings/?$ view.php?page=/rankings/ [L]
    RewriteRule ^tournaments/?$ view.php?page=/tournaments/ [L]
    </IfModule>
    

    现在唯一的错误是/news/name-of-story/有效,但没有最终/,如果有人访问/news/name-of-story,它就会中断。

    如果我的数字海洋以与XAMPP相同的方式工作,我会感到惊讶,但是当我来到它时我会越过那座桥=]

    更新:下午13:51

    我还添加了

    RewriteRule ^news/(.*) news.php?slug=/news/$1/ [L]

    处理缺少尾部斜杠

2 个答案:

答案 0 :(得分:3)

  

[L]表示如果规则匹配,则不再处理此规则以下的RewriteRules。

未经测试,但应该是:

RewriteEngine On
RewriteBase /the-site-name/
RewriteCond %{SCRIPT_FILENAME} !-f
RewriteCond %{SCRIPT_FILENAME} !-d
RewriteRule ^news/(.*)/([0-9]+) news.php?slug=/news/$1 [L]
RewriteRule ^tournaments/(.*)/([0-9]+) view.php?page=/tournaments/$1 [L]
RewriteRule ^rankings/(.*)/([0-9]+) view.php?page=/rankings/$1 [L]

更新(已测试) - 注意:已添加/$2(可能不是您想要的,可以将其删除)

RewriteEngine On
RewriteBase /the-site-name/
RewriteCond %{SCRIPT_FILENAME} !-f
RewriteCond %{SCRIPT_FILENAME} !-d
RewriteRule ^news/?$ news.php?slug=/news/ [L]
RewriteRule ^news/(.*)/?([0-9]*) news.php?slug=/news/$1/$2 [L]
RewriteRule ^rankings/?$ view.php?page=/rankings/ [L]
RewriteRule ^rankings/(.*)/([0-9]+) view.php?page=/rankings/$1/$2 [L]
RewriteRule ^tournaments/?$ view.php?page=/tournaments/ [L]
RewriteRule ^tournaments/(.*)/([0-9]+) view.php?page=/tournaments/$1/$2 [L]

说明:

^news/?$   # For "news" or "news/"
^news/(.*)/([0-9]+) news.php?slug=/news/$1/$2 # Added $2 for the second capture group

答案 1 :(得分:0)

我现在无法测试这一点,但从我记忆中来看,这些线条会导致:

L = map(list, L)

RewriteCond %{SCRIPT_FILENAME} !-f RewriteCond %{SCRIPT_FILENAME} !-d RewriteRule . /news.php [L] 基本上是'重写所有不是news.php的文件或目录的路径'。

.的工作原理如下:

RewriteRule

模式RewriteRule Pattern Substitution 意味着什么,可能导致问题。

尝试取出这些内容:

.