how to fix URL Resolve, 301 redirects in the htaccess file

Viewed 346

I'm a novice and I work PHP. My professor introduced a site that gives me website problems. (woorank) My site has a problem with 301 redirects. Look at the picture below.

Click to see my problem

My problem is and I want to resolve this problem in the .htaccess file. I knew the following code answered this but was wrong

// URL Resolve
if (currentUrl() == "http://example.com") {
    redirectToMainDomain();
} elseif (currentUrl() == "http://www.example.com") {
    redirectToMainDomain();
} elseif (currentUrl() == "https://example.com") {
    redirectToMainDomain();
} elseif (currentUrl() == "https://www.example.com") {
    redirectToMainDomain();
}

I wrote the above code on the first line of codes, but my problem was not resolved, I do something like this to apply in the .htaccess file.

if (currentUrl() == "https://www.example.com" or currentUrl() == "https://example.com" or currentUrl() == "http://example.com" or currentUrl() == "http://www.example.com") {
        header("Location: https://example.com");
        exit;
    }
if (currentUrl() == "https://www.example.com/blog/index.php" or currentUrl() == "https://example.com/blog/index.php" or currentUrl() == "http://example.com/blog/index.php" or currentUrl() == "http://www.example.com/blog/index.php") {
        header("Location: https://example.com/blog/index.php");
        exit;
    } 
// and other pages

Please guide

3 Answers

Your site URLs with or without https and www point to different locations that is why your are seeing the redirect error. You can fix this using the following code in your htaccess file:

RewriteEngine on

# rediret http and non-www to https://www
RewriteCond %{HTTPS} off [OR]
RewriteCond %{HTTP_HOST} ^example\.com$ [NC]
RewriteRule ^ https://www.example.com%{REQUEST_URI} [L,R=301]

Change example.com to your domain in the code above and test it after clearing your browser cache.

RewriteEngine On
RewriteRule ^(.*)$ http://example2.com/ [R=301]

Add this to the .htaccess which is located in the root folder of your site.

I am the author of the question. You can fix this using the following code in your .htaccess file:

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