【问题标题】:Htaccess - Add .html when needed - WordpressHtaccess - 在需要时添加 .html - Wordpress
【发布时间】:2017-11-14 03:27:14
【问题描述】:

我想为所有未使用此扩展名的页面添加 .html 扩展名。我想在存在 .html 的页面时执行此操作。 我已经尝试了很多我见过的代码,但在这个意义上没有任何效果。也许有一些不同于 htaccess 的东西可以做到这一点。 我唯一得到的就是在页面以 / 结尾时添加 .html 扩展名。 网络是用wordpress制作的,所以如果你知道任何插件或可以做到这一点的东西,请告诉我:)

我在 .htaccess 中的初始代码是:

# Do not do anything for already existing files and folders
RewriteCond %{REQUEST_FILENAME} -f [OR]
RewriteCond %{REQUEST_FILENAME} -d
RewriteRule .+ - [L]

# add .html file extension (if such file does exist)
RewriteCond %{DOCUMENT_ROOT}/$1\.html -f
RewriteRule ^(.+[^/])/?$ $1.html [L,QSA]

非常感谢您的回答!

【问题讨论】:

  • 您需要确保RewriteCond 测试-f“是一个文件”。这是你的提示;)
  • 下次你问的时候,添加你目前尝试过的代码。

标签: php html wordpress .htaccess


【解决方案1】:

很简单:

Options +FollowSymlinks
RewriteEngine On
RewriteBase /
# If /foo/bar does not exist as a file (and)
RewriteCond %{REQUEST_FILENAME} !-f
# If /foo/bar does not exist as a directory (and)
RewriteCond %{REQUEST_FILENAME} !-d
# If /foo/bar.html exists as a file
RewriteCond %{REQUEST_FILENAME}.html -f
# If above three conditions match, append .html
# stopping any other rewrite rules below this (L=last)
# and adding query string (QSA=Query String Append) such as ?a=b&c=d
RewriteRule ^(.+)$ /$1.html [L,QSA]

【讨论】:

  • 这不起作用!感谢您的回答,但是当我编写没有 .html 扩展名的 URL 时,它会将我返回到 404。
  • url 是否符合 cmets 中所写的所有条件?
  • 问题是html扩展名的文件不存在。我正在使用 wordpress,我认为我必须对每种情况做一个正则表达式。你知道如何在.httaccess 中做正则表达式吗?
  • 您另有说明,“我想在存在 .html 的页面时执行此操作”。如果您使用的是 wordpress,您只需要更改永久链接结构(设置 > 永久链接)。 Wordpress 路由任何物理上不存在于服务器上的请求,以便为正确的页面提供服务。如果您更改永久链接,wordpress 将自动更新菜单中的超链接。
  • 我知道,我已将扩展名 .html 添加到所有页面但我想要的是当 URL 没有 .html 扩展名并且与 .html 一起存在时,我想将其重定向到带有 .html 的 URL
【解决方案2】:

问题是有好几次我不需要扩展,所以我找到了一个可以做到这一点的 wordpress 插件,我还在 php 中使用了一个小函数来检查 url 中的单词是否添加。 html 扩展名。

我用过的插件名称是:

通过dr.code.skm在页面上附加扩展

功能类似这样:

function my_page_template_redirect()
{
    global $wp;
    $current_url = home_url(add_query_arg(array(),$wp->request));   
    if ( !strpos($current_url, '.html') && !strpos($current_url, 'wp-admin') && !strpos($current_url, 'wp-login') ) {
        if(!is_front_page()){
            wp_safe_redirect( $current_url.'.html' );   
        }       
    }   
}
add_action( 'template_redirect', 'my_page_template_redirect' );

感谢您的帮助!

【讨论】:

  • 该解决方案适用于页面,但在预览帖子时会产生问题。如何克服它?
  • 对不起@sumitchauhan,但我没有使用该项目的预览,所以对我来说就像一个魅力。
猜你喜欢
  • 1970-01-01
  • 2011-06-01
  • 2020-05-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多