【问题标题】:Redirecting an absolute path in a .htaccess file重定向 .htaccess 文件中的绝对路径
【发布时间】:2013-02-15 23:32:23
【问题描述】:

我有这个网站,以前页面的 URL 类似于:

请注意,这些 URL 中的任何一个都没有扩展名,即使它们是 .php 文件。这是一个位于域根目录中的 Wordpress 站点。 wordpress-site 现在已被移动到一个文件夹中,但我想设置从所有以前的 URL 到新 URL 的重定向(出于 SEO 原因)。

到目前为止,我找到了一个远非完美的临时解决方案。我所做的是将它放在 .htaccess 文件中(以删除 PHP 扩展):

  # Turn on the rewrite engine
  RewriteEngine  on
  # If the request doesn't end in .php (Case insensitive) continue processing rules
  RewriteCond %{REQUEST_URI} !\.php$ [NC]
  # If the request doesn't end in a slash continue processing the rules
  RewriteCond %{REQUEST_URI} [^/]$
  # Rewrite the request with a .php extension. L means this is the 'Last' rule
  RewriteRule ^(.*)$ $1.php [L]

然后我创建了与以前的 URL 相同的不同文件(使用 .php 扩展名,然后由于我的 .htaccess 文件而被删除)。在每个文件的顶部,我插入了一个

  <?php header('Location: THE_NEW_URL'); ?>

它有效,但它像贝蒂一样丑陋! 最近,由于这个临时的、愚蠢的解决我的问题,我遇到了一个错误。我试图在文件夹的根目录中设置一个新页面(称为 test.php)。这个 test.php 文件有一个样式表,它链接到以下方式(很标准,我假设):

     <link href="css/style.css" rel="stylesheet" type="text/css" />

但是 test.php 文件找不到这个样式表(是的,我确定我上传正确)。如果我转到源文件并单击它,那么我可以看到它试图访问

     css/style.css.php

您不必是爱因斯坦就知道,这是我在狼群中提出的 .htaccess 文件。但是我该怎么办?有没有办法制作我的 .htaccess 文件,所以我可以按照以下方式做一些事情:

     Redirect from SPECIFIC_URL to A_NEW_SPECIFIC_URL

它不会搞砸我域中的所有 URL。我喜欢在我的文件上有扩展名。我只需要修复这 15 个现在已被移动(没有扩展名)的旧 URL。

我很喜欢 .htaccess-files 并且在任何地方都找不到任何教程。糟透了!我不知道如何变得更好。我一直在执行我不理解的解决方案!?!

【问题讨论】:

    标签: php .htaccess redirect


    【解决方案1】:

    我相信这会满足您的需求:

       <IfModule mod_rewrite.c>
          # enable URI rewrite 
          RewriteEngine on
          # set virtual root
          RewriteBase /
          # if request is for an actual file or directory on disk,
          # then do not continue with rewrite engine
          RewriteCond %{REQUEST_FILENAME} !-d
          RewriteCond %{REQUEST_FILENAME} !-f
          # setup rewrite table
          RewriteRule ^page1$ page1.php [R=302,L]
          RewriteRule ^page2$ page2.php [R=302,L]
          RewriteRule ^page3$ page3.php [R=302,L]
        </IfModule>
    

    只需在现有条件的上方添加这两条 RewriteCond 行,您可能会发现成功:

      RewriteCond %{REQUEST_FILENAME} !-d
      RewriteCond %{REQUEST_FILENAME} !-f
    

    【讨论】:

    • +1 表示 RewriteCond %{REQUEST_FILENAME} !-f,但不要在 RewriteRule 替换中转义 \.
    • 哎呀——好电话;编辑并删除了不必要的转义。
    【解决方案2】:

    如果只有 15 个旧文件,一个简单的解决方案是硬编码这 15 个文件

    RewriteEngine on
    RewriteRule ^/?oldfile1$ /new1/path1/file1.php [R,L]
    RewriteRule ^/?oldfile2$ /new2/path2/file2.php [R,L]
    RewriteRule ^/?oldfile3$ /new3/path3/file3.php [R,L]
    ...
    

    【讨论】:

    • 看起来也可以。内森只是更快,而且它适用于他的方法。不过,谢谢。
    猜你喜欢
    • 2017-04-02
    • 1970-01-01
    • 1970-01-01
    • 2021-04-05
    • 1970-01-01
    • 2021-11-10
    • 2021-05-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多