【发布时间】:2020-09-17 02:27:59
【问题描述】:
我在https://searchglutenfree.com/ 有一个 React 应用程序的 htaccess 文件。我希望它自动将https://www.searchglutenfree.com/ 重写为https://searchglutenfree.com/,同时在重定向期间保留所有参数。
我在 GitHub (https://gist.github.com/iheartmedia-matt/253ccb6183fdeaa5619f615f2cb5a58b) 上找到了这个很棒的默认 htaccess 模板,并且让 www 重定向是我最不需要的。有谁知道我需要添加什么以及在文件中的哪个位置进行 WWW 重写?
<ifModule mod_rewrite.c>
#######################################################################
# GENERAL #
#######################################################################
# Make apache follow sym links to files
Options +FollowSymLinks
# If somebody opens a folder, hide all files from the resulting folder list
IndexIgnore */*
#######################################################################
# REWRITING #
#######################################################################
# Enable rewriting
RewriteEngine On
# If its not HTTPS
RewriteCond %{HTTPS} off
# Comment out the RewriteCond above, and uncomment the RewriteCond below if you're using a load balancer (e.g. CloudFlare) for SSL
# RewriteCond %{HTTP:X-Forwarded-Proto} !https
# Redirect to the same URL with https://, ignoring all further rules if this one is in effect
RewriteRule ^(.*) https://%{HTTP_HOST}/$1 [R,L]
# If we get to here, it means we are on https://
# If the file with the specified name in the browser doesn't exist
RewriteCond %{REQUEST_FILENAME} !-f
# and the directory with the specified name in the browser doesn't exist
RewriteCond %{REQUEST_FILENAME} !-d
# and we are not opening the root already (otherwise we get a redirect loop)
RewriteCond %{REQUEST_FILENAME} !\/$
# Rewrite all requests to the root
RewriteRule ^(.*) /
</ifModule>
<IfModule mod_headers.c>
# Do not cache sw.js, required for offline-first updates.
<FilesMatch "sw\.js$">
Header set Cache-Control "private, no-cache, no-store, proxy-revalidate, no-transform"
Header set Pragma "no-cache"
</FilesMatch>
</IfModule>
【问题讨论】:
-
见:
https://stackoverflow.com/questions/6515081/htaccess-remove-www-from-url-directories -
感谢@hacker315,我实际上在文件的几个不同位置插入了这段代码,但它对我不起作用。也许我错过了什么?
-
如果您不需要这对于主机名是动态的,那么我会在检查
%{HTTPS} off之后添加一个检查主机名是否以www.开头的条件,并将[OR]标志添加到前者 - 然后只需在以下规则的替换 URL 中硬编码主机名。 -
谢谢@CBroe。我对 htaccess 真的很不好,所以我要找的是确切的代码。我有一个赏金所以如果你回答确切的变化并且它有效,我会奖励你:)
-
添加了一个答案,基本上应该这样工作。如果您在我提到的 cmets 之后保留其余的重写,那么一切都应该正常工作。 (在这里说应该,因为这些事情并不总是很容易获得 100% 正确,无法在实际系统上进行测试。如果您遇到任何问题,请告诉我。)
标签: .htaccess