How to force a website to redirect from http to https using htaccess

Here am going to explain you how force a website redirect from http to https using htaccess files, we all know htaccess is the configuration files normally using in Apache web server to specify redirect rules.we can write our own URL redirect rules and based on we can change the entire website url structure.

Most common use of URL redirects for SEO purpose and better page readability/simplicity, we have lots of rule for redirecting here am going to explain you reule to redirect from http to https using htaccess files

See below force a website redirect from http to https using htaccess
This is full .htaccess to files redirect from http to https

RewriteEngine On
RewriteCond %{HTTP_HOST} ^(www\.)?tutorialshore\.com
RewriteRule ^(.*)$ https://www.tutorialshore.com/$1 [R,L]

Step 1

First you have to activate RewriteEngine

RewriteEngine On

Step 2

Check if the browser is requesting by http

RewriteCond %{HTTP_HOST} ^(www\.)?tutorialshore\.com

Step 3

if the browser is requesting by http then force to redirect to https

RewriteRule ^(.*)$ https://www.tutorialshore.com/$1 [R,L]


How to force website redirect from http to https using htaccess

Or we can use below code


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

why google shows the wrong title for my website

Nowadays many of the website show different title character in google search page ,this is actually done by the hackers, the will replace our original title with Japanese ,Slavic languages, Indo-European languages, East Slavic languages, Balto-Slavic languages any of the languages with our website title this is why google shows the wrong title for my website. Here am going to explain how to remove that hack or spammers and bring back our current title to google search result page.

See below Images google shows the wrong title for my website

why google shows the wrong title for my website

How to remove wrong title for my website

Step 1
Open google and search

site:tutorialshore.com japan **replace tutorialshore.com with yourdomain.com

site:tutorialshore.com Slavic

open the pages code, that listing in the google search result and remove any unwanted code if their that may be done my hackers

Step 2

Open your sitemap.xml page and double confirm all the URL listed in the site map are correct URL in the website, if you find anything regenerate sitemap and resubmit to google webmaster

Step 3

Sort Files by date of modified and find out any new files update without your permission

Step 4

check file permission if any having 444 permission delete that files and upload the same files from your backup.

Step 5

Open google webmaster account

report the hacked pages and remove it with the help of google webmaster

Step 6

Resubmit Sitemap and Recrawl

Open Crawl => Fetch as google =>Fetch and render

See in picture

why google shows the wrong title for my website

Creating a python application from scratch

  1.  Install Django

!) pip install “django>=2.1,<2.2”

!!) django-admin startproject metro

!!!)  python manage.py startapp metroshop

!v) python manage.py runserver

v) python manage.py createsuperuser

 

  • Change Metro Project setting.py add Metroshop

 


INSTALLED_APPS = [

    'metroshop.apps.MetroshopConfig',

    'django.contrib.admin',

    'django.contrib.auth',

    'django.contrib.contenttypes',

    'django.contrib.sessions',

    'django.contrib.messages',

    'django.contrib.staticfiles',

]

TEMPLATES = [

    {

        'BACKEND': 'django.template.backends.django.DjangoTemplates',

        'DIRS': [os.path.join(BASE_DIR, 'templates')],

        'APP_DIRS': True,

        'OPTIONS': {

            'context_processors': [

                'django.template.context_processors.debug',

                'django.template.context_processors.request',

                'django.contrib.auth.context_processors.auth',

                'django.contrib.messages.context_processors.messages',

            ],

        },

    },

]

 

WSGI_APPLICATION = 'metro.wsgi.application'

 

 

# Database

# https://docs.djangoproject.com/en/2.1/ref/settings/#databases

 

DATABASES = {

    'default': {

        'ENGINE': 'django.db.backends.sqlite3',

        'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),

    }

}

 

 

# Password validation

# https://docs.djangoproject.com/en/2.1/ref/settings/#auth-password-validators

 

AUTH_PASSWORD_VALIDATORS = [

    {

        'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',

    },

    {

        'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',

    },

    {

        'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',

    },

    {

        'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',

    },

]

 

  • Metro Project url.py add Metroshop app URL

 

from django.contrib import admin

from django.urls import path, include

from django.urls import path

 

urlpatterns = [

    path('admin/', admin.site.urls),

    path('', include('metroshop.urls')),

 path('metroshop/', include('metroshop.urls')),

]

 

 
  • Create url.py inside meroshop folder
    from django.urls import path from . import views   urlpatterns = [     path('', views.index, name='index'),     path('master_config', views.master_config, name='master_config'),     path('master_config_update', views.master_config_update, name='master_config_update'),   ]

 

  • Update view.py files with new view functions

 

 

from django.shortcuts import render, get_object_or_404

from django.http import HttpResponseRedirect

from .models import  Master_config

 

from django.urls import reverse

from django.utils import timezone

from django.contrib.auth.decorators import login_required

from django.http import HttpResponse

import json

 

# Create your views here.

#@login_required

def index(request):

 

    #return render(request, 'metroshop/test.html')

 

    return render(request, 'metroshop/salesbill.html')

 

def master_config(request):

 

    m_config =  Master_config.objects.filter()

 

    return render(request, 'metroshop/master_config.html', {'m_config': m_config})

 

def master_config_update(request):

    company_name = request.POST['company_name']

    company_mobile = request.POST['company_mobile']

    company_address = request.POST['company_address']

    company_code = 1

    a = Master_config(company_code=company_code,company_name=company_name,company_mobile=company_mobile,company_address=company_address)

    s= a.save()

    m_config = Master_config.objects.filter()

 

    return render(request, 'metroshop/master_config.html', {'m_config': m_config})

 
  • define new model model.py
  from django.db import models import math from django.core.validators import MinValueValidator, MaxValueValidator from django.contrib.auth.models import AbstractUser from django.db.models.signals import post_save, post_delete from datetime import timedelta, date   # Create your models here. class Master_config(models.Model):       company_code = models.CharField(primary_key='True', max_length=100)     company_name = models.CharField(max_length=200)     company_mobile = models.CharField(max_length=200)     company_address = models.CharField(max_length=100)       def __str__(self):         return self.company_code

 

  • Create templates/metroshop/base.html
<!DOCTYPE html>

<html lang="en">

  <head>

 

    <meta charset="utf-8">

    <meta http-equiv="X-UA-Compatible" content="IE=edge">

    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">

    <meta name="description" content="">

    <meta name="author" content="">

 

    <title>{% block title %}{% endblock %}</title>

    {% load static %}

 

       <!-- Bootstrap core CSS -->

       <link href="{% static '/metroshop/homepage/vendor/bootstrap/css/bootstrap.min.css' %}" rel="stylesheet">

       <link href="{% static '/metroshop/css/style.css' %}" rel="stylesheet">

     <!-- Custom styles for this template-->

     <link href="{% static '/metroshop/bootstrap/css/sb-admin.css' %}" rel="stylesheet">

 

     <!-- Custom styles for this template -->

 

 

    <link rel="stylesheet" href="http://code.jquery.com/ui/1.8.18/themes/base/jquery-ui.css" type="text/css" media="all" />

 

 

    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>

    <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.min.js" integrity="sha384-wfSDF2E50Y2D1uUdj0O3uMBJnjuUD4Ih7YwaYd1iqfktj0Uod8GCExl3Og8ifwB6" crossorigin="anonymous"></script>

 

    <link href="http://code.jquery.com/ui/1.10.2/themes/smoothness/jquery-ui.css" rel="Stylesheet"></link>

   <script src="https://code.jquery.com/ui/1.10.2/jquery-ui.js" ></script>

 

  </head>

 

  <body id="page-top">

 

    <nav class="navbar navbar-expand navbar-dark bg-dark static-top">

 

      <a class="navbar-brand mr-1" href="{% url 'index' %}">Metro ERP</a>

 

      <button class="btn btn-link btn-sm text-white order-1 order-sm-0" id="sidebarToggle" href="#">

        <i class="fas fa-bars"></i>

      </button>

 

      <!-- Navbar -->

        <div class="collapse navbar-collapse" id="navbarResponsive">

 

          <ul class="navbar-nav ml-auto">

            <li class="nav-item">

                {% if request.user.is_student %}

                    <a class="nav-link text-capitalize">{{ request.user.student.name }}</a>

                {% elif request.user.is_teacher %}

                    <a class="nav-link text-capitalize">{{ request.user.teacher.name }}</a>

                {% endif %}

            </li>

            <li class="nav-item">

                <a class="nav-link" href="#" data-toggle="modal" data-target="#logoutModal">Logout</a>

            </li>

          </ul>

        </div>

 

    </nav>

 

    <div id="wrapper">

 

      <!-- Sidebar -->

      <ul id="nav" class="sidebar navbar-nav">

 

        <li class="nav-item">

          <a class="nav-link" href="{% url 'index' %}">

            <span>Home</span>

          </a>

        </li>

        <li><a href="#" class="sub" tabindex="1">Master</a><img src="{% static 'metroshop/images/up.gif' %}"  alt="" />

          <ul>

            <li><a  href="{% url 'master_config' %}">

              <span>Config Master</span>

            </a></li>

          

           

 

          </ul>

      </li>

 

    </ul>

 

 <div id="content-wrapper">

 

        <div class="container-fluid">

 

          <!-- Breadcrumbs-->

{#          <ol class="breadcrumb">#}

{#            <li class="breadcrumb-item">#}

{#              <a href="index.html">Dashboard</a>#}

{#            </li>#}

{#            <li class="breadcrumb-item active">Blank Page</li>#}

{#          </ol>#}

 

          <!-- Page Content -->

            {% block content %}

            {% endblock %}

 

        </div>

        <!-- /.container-fluid -->

 

        <!-- Sticky Footer -->

{#        <footer class="sticky-footer">#}

{#          <div class="container my-auto">#}

{#            <div class="copyright text-center my-auto">#}

{#              <span>Copyright © Your Website 2018</span>#}

{#            </div>#}

{#          </div>#}

{#        </footer>#}

 

      </div>

      <!-- /.content-wrapper -->

 

    </div>

    <!-- /#wrapper -->

 

    <!-- Scroll to Top Button-->

    <a class="scroll-to-top rounded" href="#page-top">

      <i class="fas fa-angle-up"></i>

    </a>

 

    <!-- Logout Modal-->

    <div class="modal fade" id="logoutModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">

      <div class="modal-dialog" role="document">

        <div class="modal-content">

          <div class="modal-header">

            <h5 class="modal-title" id="exampleModalLabel">Ready to Leave?</h5>

            <button class="close" type="button" data-dismiss="modal" aria-label="Close">

              <span aria-hidden="true">×</span>

            </button>

          </div>

          <div class="modal-body">Select "Logout" below if you are ready to end your current session.</div>

          <div class="modal-footer">

            <button class="btn btn-secondary" type="button" data-dismiss="modal">Cancel</button>

            <a class="btn btn-primary" href="/accounts/logout">Logout</a>

          </div>

        </div>

      </div>

    </div>

 

 

    <script src="{% static '/metroshop/js/main.js' %}" type="text/javascript"> </script>

   {% block scripts %}

    {% endblock %}

  </body>

 

</html>

 

 

 
  • Create templates/metroshop/master_config.html

 

{% extends 'metroshop/base.html' %}

{% load static %}

{% block content %}

 

    <div class="card mb-3">

            <div class="card-header">

              <i class="fas fa-table"></i>

            <b>Company Config Master</b></div>

 

            <div class="card-body">

 

              <div class="table-responsive">

                <form id="master_config" name="master_config" method="post" action="{% url 'master_config_update'  %}" enctype="">

                  {% csrf_token %}

                <table class="table table-bordered" id="dataTable" width="100%" cellspacing="0">

                  <thead>

                    <tr>

                        <th>Name </th>

                        <th>Value</th>

 

 

                    </tr>

                  </thead>

                  <tbody>

 

                    {% for Cinfo in m_config %}

 

                    {% endfor %}

                    <tr>

 

                        <td><b>company Name </b></td>

                        <td><b></b><input type="text" name="company_name" value="{{Cinfo.company_name }}"></b></td></tr><tr>

                        <td><b>company Mobile</b></td>

                        <td><b><input type="text"  name="company_mobile" value="{{Cinfo.company_mobile }}"></b></td></tr><tr>

                        <td><b>company Address</b></td>

                        <td><b></b><textarea name="company_address" >{{ Cinfo.company_address }} </textarea></b></td>

 

                    </tr>

 

                  <tr><td></td><td> <button class="submit" name="add_product_info" onClick="javascript:save_existing_product();">Submit</button></td></tr>

 

 

                  </tbody>

                </table></form>

              </div>

            </div>

          </div>

 

 

 

 

 

    {% endblock %}

<!-- Modal -->

 

 

 

  • python manage.py makemigrations

 

 

 

NameError name slugify is not defined Django error

Most of the case When you tried to add a slug keyword for page model you will get error NameError: name ‘slugify’ is not defined Django error.Here we are discussing how to solve “NameError: name ‘slugify’ is not defined Django error”

Here is the model

from django.db import models

# Create your models here.
class page(models.Model):
 """Model representing a book (but not a specific copy of a book)."""
 
 page_id = models.AutoField(primary_key=True)
 
 page_title = models.CharField(max_length=200)

 author_name = models.CharField(max_length=100)
 
 page_content = models.TextField(max_length=1000, help_text='Enter your page content')
 
 page_name = models.SlugField(editable=False) # hide from admin

 def save(self):
 if not self.page_id:
 self.page_name = slugify(self.page_title)

 super(page, self).save()

Here is the error

“NameError: name ‘slugify’ is not defined Django error”

 

NameError name slugify is not defined Django error

How to Solve it

Step install  python-slugify module

# pip install python-slugify

Include slugify module in your model
 from slugify import slugify

NameError name slugify is not defined Django error 2