วันศุกร์ที่ 13 พฤษภาคม พ.ศ. 2559

[PHP] Redirect "non-www" to "www"

ปัญหาเล็กๆ อย่างเช่น พิมพ์ www กับ ไม่พิมพ์ www
ตัวอย่างเช่น  http://www.[mydomain].com กับ http://[mydomain].com

อาจทำให้เกิดปัญหาใหญ่ๆ ได้
เช่น
  • Session ระหว่าง url ที่ "มี www" เป็นคนละตัวกับ "ไม่มี www" 
  • App Facebook Log ที่เราใส่ Site URL ได้แค่ 1 url
    ทำให้ต้องเลือกระหว่างจะพิมพ์ www หรือ แบบไม่พิมพ์ www
เป็นต้น


วิธีการแก้ไข
  • เราจะทำการ Force Redirect url ที่ "ไม่มี www"  >> ไปยัง url ที่ "มี www" 






ขั้นตอน สำหรับ Apache Server
สร้างไฟล์ .htaccess โดยใช้ script ดังนี้

# Force to www:
RewriteEngine on
RewriteCond %{HTTP_HOST} ^mydomain.com [NC]
RewriteRule ^(.*)$ http://www.mydomain.com/$1 [L,R=301,NC]




ขั้นตอน สำหรับ IIS Server
แก้ไข web.config โดยใช้ script ดังนี้

<?xml version="1.0" encoding="UTF-8"?>
<configuration>
  <system.webServer>

    <rewrite>
      <rules>
       <rule name="Redirect to WWW" stopProcessing="true">
         <match url=".*" />
         <conditions>
           <add input="{HTTP_HOST}" pattern="^mydomain.co.th$" />
         </conditions>
         <action type="Redirect" url="http://www.mydomain.co.th/{R:0}" redirectType="Permanent" />
       </rule>
      </rules>
    </rewrite>

  </system.webServer>
</configuration>