htaccess | Apache
ref. https://httpd.apache.org/docs/current/mod/mod_rewrite.html
RedirectとRewrite
Rewrite
mod_rewriteが有効な場合にのみ処理をする。
<IfModule mod_rewrite.c>
RewriteEngine on
# 処理
</IfModule>
Ref
ディレクティブ
- RewriteEngine
- RewriteCond:「文字列が正規表現に合致したときに次の行のRewriteRuleを実行」
- 用法: RewriteCond 文字列 正規表現
- RewriteRule:「mod_rewriteの書き換えルールを設定する」
- 用法: RewriteRule 正規表現 書き換え後 [フラグ]
例)http -> https
blogディレクトリを除いてSSL化。
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteCond %{HTTPS} !on
RewriteCond %{REQUEST_URI} !(^/blog/)
RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [R=301,L]
</IfModule>
例)WordPress
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
</IfModule>
.htaccess上では、リダイレクト元のパターン指定は、ホスト名直後のスラッシュを含まないURLパス、逆に、リダイレクト先はホスト名直後のスラッシュを含むパスとなります。これはApache の仕様で定義されていますが、混乱しやすいため、注意が必要です。
参考:RewriteRule directive: What is matched?
Redirect
特定ページをRedirect
通常
301リダイレクトの記述
Redirect permanent /sample/ http://www.example.com/index.php
302リダイレクトの記述
Redirect 302 /sample/ http://www.example.com/index.php
正規表現
301リダイレクトの記述
RedirectMatch permanent ^/index\.html$ https://example.com/example/
302リダイレクトの記述
RedirectMatch 302 ^/index\.html$ https://example.com/example/
オリジン間リソース共有 (CORS)
Header set Access-Control-Allow-Origin "*"
Filesディレクティブ (Apache 2.4以降)
<Files "index.php">
Require all granted
</Files>
FilesMatchディレクティブ (Apache 2.4以降)
<FilesMatch "^composer|^COPYING|^\.env|^\.maintenance|^Procfile|^app\.json|^gulpfile\.js|^package\.json|^package-lock\.json|web\.config|^Dockerfile|\.(ini|lock|dist|git|sh|bak|swp|env|twig|yml|yaml|dockerignore)$">
Require all denied
</FilesMatch>
ref.
- https://www.javadrive.jp/apache/section/index2.html
- https://piro791.blog.ss-blog.jp/2010-03-31-1