以往 301 我都是設在 Apache 裡面,如下:
RewriteRule ^news$ http://example.com/news/ [R=301,NE,L]
想要在 PHP 送 301 / 302 Redirect 的 Header 要如何寫?
HTTP 定義 301 / 302 的 Header 意義:
- 301: 永久轉址 (Permanently Moved)
- 302: 臨時轉址 (Temporarily Moved)
PHP 送 301 / 302 轉址的 Header
PHP 301 Redirect (永久轉址)的寫法
- vim 301.php
<?php header("HTTP/1.1 301 Moved Permanently"); header("Location: http://example.com"); ?>
- vim 301.php # 新寫法
<?php header("Location: http://example.com", TRUE, 301); ?>
- $ curl -I http://localhost/301.php # 測試
HTTP/1.1 301 Moved Permanently Date: Fri, 20 Sep 2015 07:15:19 GMT Server: Apache/2.4.10 Location: http://example.com/ Content-Type: text/html; charset=UTF-8
PHP 302 Redirect 寫法
- vim 302.php
<?php header("Location: http://example.com"); ?>
- $ curl -I http://localhost/302.php # 測試
HTTP/1.1 302 Found Date: Fri, 20 Sep 2015 07:15:37 GMT Server: Apache/2.4.10 Location: http://example.com/ Content-Type: text/html; charset=UTF-8