regex - .htaccess - 强制 url 从 'dir/page.html' → 'dir/page'

标签 regex apache .htaccess mod-rewrite seo

我想删除特定文件类型的所有尾随扩展名(例如删除所有 .html 并让其他一切保持原样)

因此,例如,如果用户访问页面 <my-site>/how-to/use-git.html , 他将被重定向到 <my-site>/how-to/use-git (有或没有尾随/)。任何其他请求(如 <my-site>/how-to/img1.jpg)将保持原样(<my-site>/how-to/img1.jpg)。

在四处浏览时,我找不到满足以下条件(两者)的内容:

  • 删除.html
  • 强制转到没有扩展名的 url

我试过这样的事情

# From http://stackoverflow.com/questions/27553722/htaccess-mod-rewrite-how-to-modify-url-from-pages-pagename-cfm-to-pagename
RewriteEngine On
RewriteBase /

RewriteCond %{THE_REQUEST} \s/+pages/(.+?)\.html[\s?] [NC]
RewriteRule ^ /%1/ [R=302,L,NE]

RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{DOCUMENT_ROOT}/pages/$1\.html -f [NC]
RewriteRule ^(.+?)/?$ pages/$1.html [L]

但它并不强制页面转到没有扩展名的版本。

添加

# From http://www.webweaver.nu/html-tips/web-redirection.shtml
RedirectMatch 301 (.*)\.html$ $1

创建 404 未找到错误。

最佳答案

您可以在您的 DOCUMENT_ROOT/.htaccess 文件中使用这些规则:

RewriteEngine On

# To externally redirect /path/file.html to /path/file
RewriteCond %{THE_REQUEST} /(.+?)\.html[\s?] [NC]
RewriteRule ^ /%1 [L,R=302]

## To internally redirect /path/file to /path/file.html
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME}.html -f
RewriteRule ^(.+?)/?$ $1.html [L]

关于regex - .htaccess - 强制 url 从 'dir/page.html' → 'dir/page',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32415767/

相关文章:

.htaccess - MAMP 起始页重定向循环

.htaccess - 如何隐藏所有控制台错误

php - 允许服务器运行 cron 作业但使用 .htaccess 阻止普通用户访问

javascript - RegExp 不正确地匹配反斜杠

windows - 使用 MSysgit 的 Perl intrepretor 在 Windows 上的 Apache 下 GitWeb 非常慢

linux - 在 VPS red-hat linux 上设置 LD_LIBRARY_PATH

linux - dpkg :- error processing package javascript-common (--configure):- while using apt-get command

javascript - 在 JavaScript 中从正则表达式生成字符串

python - 具有两种可能正则表达式的子字符串

regex - 如何在 perl 中打印特定格式的数组?