よく使う.htaccess 記述(自分用メモ)


basic認証

.htaccess

.htaccess
#bacic認証
AuthUserFile /PATH_TO_FILE/.htpasswd
AuthType Basic
AuthName "Web access"
Require valid-user

.htpasswd

.htpasswd
#pw password
user:password(MD5)

MD5パスワード生成サイト
http://www.cityjp.com/cript/crpt.cgi

SSLリダイレクト

https統一

.htaccess
RewriteEngine on
RewriteCond %{HTTPS} off
RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [R=301,L]

URLを統一編

wwwなしに統一(www ❌ )

.htaccess
# wwwを無しに統一
RewriteEngine On
RewriteCond %{HTTP_HOST} ^www\.(.+)$ [NC]
RewriteRule ^(.*)$ https://%1/$1 [R=301,L]

wwwありに統一(www ⭕️ )

.htaccess
# wwwを有りに統一
RewriteEngine On
RewriteCond %{HTTP_HOST} !^www\.(.+)$ [NC]
RewriteCond %{HTTP_HOST} (.+)$ [NC]
RewriteRule ^(.*)$ https://www.%1/$1 [R=301,L]

index.htmlなしに統一

.htaccess
RewriteCond %{THE_REQUEST} ^.*/index.html
RewriteRule ^(.*)index.html$ https://www.example.com/$1 [R=301,L]

AddType編

HTMLファイルでPHP実行を有効

.htaccess
# AddTypeを使う場合
AddType application/x-httpd-php .html .htm

# AddHandlerを使う場合
AddHandler application/x-httpd-php .php .html


### XSERVER ###
#サーバー番号が2001(sv2001)以降
AddHandler fcgid-script .html

#サーバー番号が1999(sv1999)以前
AddHandler x-httpd-php5.6 .php .phps .html

### お名前.com ###
Action myphp-cgi /php.cgi
AddHandler myphp-cgi .html

お名前.comの場合
php.cgiファイル作成

php.cgi
#! /usr/bin/bash
exec /usr/local/bin/php-cgi

SVGを有効

.htaccess
AddType image/svg+xml .svg .svgz

リダイレクト編

ファイルをリダイレクト

.htaccess
Redirect permanent /cgi-bin/contact/index.cgi /contact/index.html

404エラー リダイレクト

.htaccess
ErrorDocument 404 /not_found.html

WPコンテンツをリダイレクト

.htaccess
# WPコンテンツをリダイレクト
RewriteCond %{QUERY_STRING} preview=true [OR]
RewriteCond %{REQUEST_URI} ^(/news/?)
RewriteRule (.*) /wordpress/$1

RewriteRuleでリダイレクト

.htaccess
RewriteEngine on
RewriteRule (.*) http://www.xxxxxxx.jp/ [L,R=301]

index.htmlなしにリダイレクト

.htaccess
RewriteEngine on
RewriteCond %{THE_REQUEST} ^.*/index.html
RewriteRule ^(.*)index.html$ /$1 [R=301,L]

参考サイト