user3528073
user3528073

Reputation: 55

How to make a 301 redirect from PHP?

example.com/video.php – this link should redirect to example.com/videos/.

I’ve tried but it isn’t working. I want 301 redirect.

This is my code in video.php:

<?php
// 301 redirect from php
header('Location: /videos/');
?>

I want the full code for doing this.

Upvotes: 3

Views: 6053

Answers (3)

user3501407
user3501407

Reputation: 457

Use this:

<?php 
header("HTTP/1.1 301 Moved Permanently"); 
header("Location: http://www.example.com/videos"); 
?>

The http:// is required.

Upvotes: 6

Marco Panichi
Marco Panichi

Reputation: 1185

Starting with PHP 5.4 you can simplify code output with the http_response_code() function:

<?php
    http_response_code(301);
    header("Location: http://www.example.com/videos");
?>

Upvotes: 2

Luton Datta
Luton Datta

Reputation: 54

Alternatively you can use this single line:

<?php 
header("Location: http://www.example.org/videos", TRUE, 301); exit();
?>

Remember to add exit() or die() at the end.

Upvotes: 1

Related Questions