Shorten url

Here’s why you should use link compressor to create short URL:

  1. Small URL is manageable:

    http://xyz.com/e/b17ab777-ceb6-f7fd-8411-ca3a6ca9c9d4ssa/Url-Shortener

    OR

    https://goo.gl/AxNQAr

    Which one do you find easier to share?

    Of course, not all URLs are that messy. Nonetheless, many links are often wordy and lengthy for SEO reasons. Search Engine Optimization is all about better ranking in search engines, especially Google. One of the key factors that Google or any other search engine considers are the keywords in the URL. The URLs help describe the page content, and so it becomes a challenge for the user to shrink URL and use it. Lengthy links are difficult to share in the e-mails and social media platforms like Facebook and Twitter.

    Tools like Facebook URL shortener help to create a small URL and make link shorter and more manageable.

    url shortener


  2. Useful when sharing the content

    As we all know, some social media sites such as Twitter have a character limit that doesn’t allow users to post long URLs. Therefore, the post must be relevant and concise. Best create short url tool is the one that makes a shorter web address having the more accurate information about the content that you want to share instead of having a tweet with a very long URL and misleading content. Moreover, it is recommended to brand a URL created with link compressor so that you know when it is shared.

  3. They have better aesthetic appeal

    Google URL shortener is handy when it comes to enhancing the aesthetic appeal of a URL. Short and precise URLs tend to look prettier when shared on social media. Not just limited to social media, but they are also useful when creating other types of content such as an infographic or a print ad, and you need to insert a URL. Moreover, for users on a mobile device, shorter URL is going to give them a better user experience.

  4. The shorten URL can come with traffic monitors

    If anyone is curious about the performance of the content and how is it being received by users, a custom link compressor can even allow you to track the sharing activities and behavior of your social media post over a specific period.

    However, it is essential to see if the link shortener is not negatively influencing your SEO. There is no doubt that the more the content is shared, the better it is, and it would be a shame that a link created using a free Create short URL isn’t recognized by the algorithms used by search engines.


smallseotools.com

image

Статья описывает создание простейшей сокращалки ссылок, вроде bit.ly или goo.gl.

Итак, заходим в директорию с вашим проектом и создаём приложение. Пусть оно носит имя ‘shortener’.

$ django-project startapp shortener

Для начала опишем несложную конфигурацию URL, которая будет определять, что нужно пользователю в соответствии с его запросом.

<br/># urls.py <br/>from django.conf.urls.defaults import *<br/> <br/>urlpatterns = patterns(»,<br/>   (r‘^$’, ‘views.index’),<br/>   (r‘^(?P<key>.{3})$’, ‘views.redirect’),<br/>) <br/>


Мы будем рассматривать случай, когда для сокращения используется адрес example.com, то есть представленная выше конфигурация является единственной (не забудьте указать ROOT_URLCONF в settings.py). Если же вы используете адрес вроде example.com/shortener/, не забудьте подключить свою конфигурацию в основной с помощью механизма include.

Теперь при обращении к example.com будет вызывать функция представления index из файла views.py, остальные же адреса, длина которых 3 три знака (без домена), мы будем пытаться «развернуть» помощью функции redirect из того же файла. Для сокращения ссылок мы будем использовать латинские буквы в различном регистре и цифры. Длина «ключа» будет три символа, этого вполне достаточно для не очень массовых сервисов (62^3 варианта).

Следующим нашим шагом будет определение модели, то есть описание данных на уровне БД.

# models.py <br/>from django.db import models<br/> <br/>from datetime import datetime<br/>from random import choice<br/>import string<br/> <br/> <br/>def genera.
<br/> <br/>    key = models.CharField(max_length=3, primary_key=True, default=generate_key)<br/>    target = models.URLField(verify_exists=False, unique=True)<br/>    added = models.DateTimeField(auto_now_add=True, editable=False)<br/> <br/>    def __unicode__(self):<br/>        return '%s  %s' % (self.target, self.key)<br/> <br/> <br/>class Hit(models.Model):<br/> <br/>    target = models.ForeignKey(ShortUrl)<br/>    time = models.DateTimeField(auto_now_add=True, editable=False)<br/>    referer = models.URLField(blank=True, verify_exists=False)<br/>    ip = models.IPAddressField(blank=True)<br/>    user_agent = models.CharField(blank=True, max_length=100) <br/>

После импорта нужных функций и моделей мы реализуем функцию, которая будет генерировать случайный ключ из заданных символов. Далее описывается класс ShortUrl, который отвечает за представление нашей сокращённой ссылки в базе данных. Каждый объект этого класса имеет уникальный атрибут key, поле, в котором хранится «длинная» ссылка, а также дату создания ссылки. Затем идет класс Hit. С помощью него мы будет хранить информацию о клике по укороченной ссылке, а именно время клика, IP кликнувшего, его User Agent и Referer, ну и «длинную» ссылку.

Обратите внимание на аргументы полей, впоследствии они будут очень важны.

Наша страница, на которой пользователь сможет укоротить свою ссылку, будет очень минималистичной — одна форма и одна кнопка (она показаны на первой картинке). Давайте опишем эту небольшую форму, её код будет содержаться в forms.py.

#forms.py<br/>from django import forms<br/> <br/>class UrlForm(forms.Form): <br/>    url = forms.URLField(label='url', verify_exists=False) <br/>

Здесь всё очень просто — одно поле, с помощью которого мы будем обрабатывать отправленную пользователем «длинную» ссылку.

Пришло время написать представление, которое будет обрабатывать данные, переданные нашей конфигурацией URL. Первой опишем функцию make_short_url и импортируем нужные модули и функции.

#views.py<br/>from django.http import HttpResponseRedirect<br/>from django.shortcuts import render_to_response, get_object_or_404<br/>from django.template import RequestContext<br/> <br/>from forms import UrlForm<br/>from models import ShortUrl, Hit<br/> <br/> <br/>def make_short_url(url):<br/>    short_url = ShortUrl.objects.get_or_create(target=url)[0]<br/>    short_url.save()<br/>    return 'http://example.com/%s' % (short_url.key)<br/>

После импортов реализуется функция, которая принимает некую ссылку, создаёт соответствующий ей объект класса ShortUrl и возвращает уже укороченную ссылку (она была сгенерирована во время создания объекта). Возможно также использование Site.objects.get_current().domain из django.contrib.sites.models.

Теперь нам нужно написать функции, которые обрабатывают форму и реализуют разворачивание «короткой» ссылки, то есть редирект.

#views.py (continuation)<br/>def index(request):<br/>    if request.method == 'POST':<br/>        form = UrlForm(request.POST)<br/>        if form.is_valid():<br/>            url = form.cleaned_data.get('url')<br/>            url = make_short_url(url)<br/>            'url': ''})<br/> <br/> <br/>def redirect(request, key):<br/>    target = get_object_or_404(ShortUrl, key=key)<br/> <br/>    try:<br/>        hit = Hit()<br/>        hit.target = target<br/>        hit.referer = request.META.get("HTTP_REFERER", "")<br/>        hit.ip = request.META.get("REMOTE_ADDR", "")<br/>        hit.user_agent = request.META.get("HTTP_USER_AGENT", "")<br/>        hit.save()<br/>    except IntegrityError:<br/>        pass<br/> <br/>    return HttpResponseRedirect(target.target) <br/>

Функция index отображает пустую форму, если пользователь ещё не обращался к ней, и обрабадывает её в случае POST запроса. В первом случае шаблону shortener.html, который отвечает за интерфейс передаётся сама форма и пустая ссылка, во втором — только укороченная ссылка. Далее следует функция redirect, к которой обращается конфигурация URL, если она сочла обращение пользователя за просьбу развернуть «короткую» ссылку. Перед простым редиректом мы создаём объект класса Hit, описанного в models.py, с соответствующими атрибутами, полученными из объекта request. Ещё советую почитать комментарии, в них много интересного про конструкцию «except: pass».

Осталось совсем чуть-чуть, еще немного и у нас будет своя сокращалка ссылок!

Настало время описать наш шаблон shortener.html, отвечающий за HTML представление формы и укороченной ссылки. Вспомните, какие параметры он принимает.

<input type="submit" name="submit" value="submit"/><br/>    </form><br/>{% else %}<br/>        <a href="{{url}}"></a>{{ url }}</a><br/>{% endif %} <br/>

В принципе, вы уже можете использовать этот код — сам URL Shortener уже создан. Осталось описать представление наших данных в интерфейсе администратора (не забудьте подключить соответствующую конфигурацию в файле urls.py).

#admin.py<br/>from django.contrib import admin<br/> <br/>from models import ShortUrl, Hit<br/> <br/> <br/>class ShortUrlAdmin(admin.ModelAdmin):<br/>    fields = ('target', 'key')<br/>    list_display = ('key', 'target', 'added')<br/>    ordering = ('-added',)<br/>    list_filter = ('added',)<br/>    date_hierarchy = 'added'<br/> <br/>admin.site.register(ShortUrl, ShortUrlAdmin)<br/> <br/> <br/>class HitAdmin(admin.ModelAdmin):<br/>    list_display = ('target', 'ip', 'user_agent', 'referer', 'time')<br/>    ordering = ('-time',)<br/>    list_filter = ('target', 'referer', 'time')<br/>    date_hierarchy = 'time'<br/> <br/>admin.site.register(Hit, HitAdmin) <br/>

Вот и всё. Осталось выполнить

$ python manage.py syncdb

И наслаждаться результатом 🙂

Интерфейс администратора:

image

image

Результат работы нашего URL Shortener’a:

image

Попробовать его вы можете здесь.

habr.com

The 8 Best URL Shortener Services

  • Bitly
  • Bl.ink
  • Polr
  • Rebrandly
  • T2M
  • TinyURL
  • URL Shortener by Zapier
  • Yourls

Bitly

Best URL shortener for businesses branding and tracking links

Bitly is a full service, business-grade URL shortener, although if your needs are modest, you can also use it anonymously to shorten long URLs and be on your way. But it stands out for its business offering. Part of the appeal is that Bit.ly is simple and easy to use. It has a comprehensive dashboard where you can track statistics about your links, such as click-through rates, geographic data of people visiting your links, and so forth. Tools for tracking campaigns are easy to use as well.

With Bitly’s free limited account, you can customize your shortened URLs, track click rates, and get information about your top referrers, but only for 500 branded links and 10,000 non-branded links. It’s a generous free plan and could very well be adequate for some small businesses. Enterprise-grade accounts (custom pricing) allow you to make as many branded links as you want, plus see more data in reports about who clicks your links. Bitly is the best URL shortener for large businesses looking to brand and track links, and it’s a great choice for small businesses that want to generate short URLs and follow their stats for a modest number of campaigns. Bitly integrates with Zapier, which means you can automate it with any other tool that supports Zapier.


Bl.ink

Best URL shortener for small businesses

Bl.ink is a full-featured URL shortener service that you use it to not only turn long URLs into short ones but also track the traffic coming from your links. Its dashboard shows trending links and general statistics, while an analytics page lets you dive into traffic by device, location, and referrers. You can also drill down into clicks by the time of day. Tags, which you can add to your shortened links, let you view your link traffic in new and custom ways.

Bl.ink offers four tiers of paid plans, starting at $12/month, to give small businesses, teams, and enterprises a variety of options, based on the number of links you need to generate and track. Free account holders can generate 1,000 links and track up to 1,000 clicks per link. Free accounts can connect to one domain for making branded links. If you’re a business in need of a full-service URL shortener and Bitly’s enterprise-grade plan seems like overkill, then Bl.ink’s is one of your best options. Bl.ink is supported by Zapier, meaning you can connect it to other apps you use in your work to generate and track short links automatically.


Polr

Best URL shortener for self-hosting

Open-source project Polr allows people with the technical know-how to host their own URL shortener. It’s available through the Polr project page and from GitHub. You can use the tool as-is or fork it if you have the programming abilities to do so. (If you’re so inclined, it’s written in PHP and Lumen, using MySQL as its primary database.) Though it’s similar to Yourls, another free and open source URL shortener, Polr is much slicker looking, designed to have a modern and minimalist feel. It comes with some traffic tracking tools as well. If you just want to test out the basic interface, Polr offers a demo page.


Rebrandly

Best URL shortener for creating branded links

While Rebrandly is a URL shortener much like any other, its angle is slightly different. Rebrandly believes that brands, whether it’s a product or a person, get value out of customizing links to content that references them from all over the web. For example, Bob Vila could customize the link to his Wikipedia entry from en.wikipedia.org/wiki/Bob_Vila to BobVila.Tools/wikipedia. A link to one of his books on Amazon could be BobVila.Tools/amazon-book. Vila can use these links on his own site, business cards, or in advertisements. Rebrandly includes tools for tracking the popularity of each link, too. Rebrandly supports QR code generation, too. (If Rebrandly is more than you need, is.gd works for QR generation as well.) A free account includes 500 links on five custom domains. Paid plans start at $29/month. Zapier supports Rebrandly, so you can integrate it with other apps with ease.


T2M

Best for making short links and QR codes simultaneously

T2M, also called T2Mio, is another full service URL shortener where you can see a dashboard of activity and other statistics for tracking URL traffic. It has two dashboards, one for geographic information and one for device and platform, that are especially well designed and easy to read. When you spin up a URL, T2M also automatically generates a QR code, a nice touch if you need it. Another unique feature is a tool that helps you target specific geographic locations where you want your URLs to have an effect. The site could stand to have more information about this particular tool, as it’s vague about what it does exactly, but overall the features and interface are well thought out.

Similar to its competitors, T2M has a free plan with limitations, plus paid accounts for those who need more. The free plan does not put any limits on the number of URLs you can generate, nor how many clicks you can track. It also gives you baked in tools for sharing shortened URLs on social networking sites. A Standard plan that’s suited for small businesses costs $7/month and adds branded and vanity URLs, password protected URLs, a tool for shortening a number of URLs at once («bulk changer»), the ability to add one custom domain, and a few additional perks. There’s an Enterprise plan, too, that removes very nearly all limits found in the Standard plan and adds some additional features as well, which costs $67/month. T2M is a very good URL shortener for businesses that want pleasing dashboards and automatic QR code generation.


TinyURL

Best URL shortener for quick, anonymous use

Free URL shortener TinyURL has been in the game since 2002, and for good reason. It’s a wonderful tool when you need to create a short link in a hurry that will never expire. TinyURL can suggest a shorter URL for you, or you can customize the result, although it will start with tinyurl.com/. TinyURL also offers a toolbar button that lets you generate a short link from the current webpage on screen. It’s a little different from a typical browser plugin. On TinyURL’s main page, there are instructions to drag a link from the page into your toolbar’s links section. That link is actually a little script. From any web page, you can click that link and it will take you back to TinyURL where a shortened link will have already been generated for the page where you started. Although TinyURL is entirely free and anonymous to use, it doesn’t contain any reports or information about your links and their popularity.


URL Shortener by Zapier

Best URL shortener for generating links automatically

When you want to automatically create and save a shortened link every time you do a certain action (I’ll give an example in a moment), Zapier’s URL Shortener is one of the best options. Formerly part of Zapier’s Formatter, the URL Shortener is now its own tool that can automatically shorten links. For example, every time you post a new photo to Flickr, you want to generate a shorter link and save a copy of it to a Google Sheet. You can create a Zap, what we call Zapier’s automated workflows, to do just that, and from there on out, all you have to do is upload your images to Flickr and Zapier will do the rest. Another very good option along the same lines is Owly, which was once a standalone apps but is now a tool within Hootsuite. You can use Owly to automatically shorten a link everytime you schedule a social media update to post. It’s a handy tool for a specific use case, but not as flexible as the other URL shorteners on this list.


Yourls

Best URL shortener for self-hosting and customizing

Yourls, which is an acronym for «your own URL shortener,» is not an off-the-shelf URL shortening service, but rather one that you install and run on your own server. Similar to Polr, Yourls is free and open-source. With Yourls, you can choose whether your links will be public or private. It includes bookmarklets, which let you turn a long URL into short one from your web browser in just one click. By default, the tool generates sequential URLs, but you can change it to come up with random strings instead if you prefer. There are a few traffic tracking tools as well.

This URL shortener was designed to be lightweight rather than bloated with features, but if you want to expand its capabilities, you can install plugins for Yourls or build your own plugins for it.


As you look for a URL shortening service that’s right for you, rest easy knowing any links made with goo.gl will continue to work as normal after Google pulls the plug.

Title image from FreeImages.com/ Anna Maria Lopez Lopez.

zapier.com


You May Also Like

About the Author: admind

Добавить комментарий

Ваш e-mail не будет опубликован. Обязательные поля помечены *

Этот сайт использует Akismet для борьбы со спамом. Узнайте как обрабатываются ваши данные комментариев.

Adblock
detector