Бесплатный Кодировщик URL Онлайн

Кодирование текста для безопасного использования в URL. Преобразует специальные символы в процентно-кодированный формат.

0 символов

Что такое кодирование URL?

Кодирование URL, также известное как процентное кодирование, — это механизм кодирования специальных символов в URL. URL могут содержать только определённые символы из набора ASCII, поэтому другие символы должны быть преобразованы в допустимый формат.

Common Uses of URL Encoding

  • Query String Parameters: When building URLs with query parameters, encode both keys and values to prevent breaking the URL structure. For example, "search=coffee & tea" becomes "search=coffee%20%26%20tea". Without encoding, the & would be interpreted as a parameter separator, not part of the search term. This is the most common use case. Every search form, filter, or API with query parameters requires URL encoding.
  • API Endpoint Construction: REST APIs often include parameters in the URL path or query string. When calling APIs with user input, special characters, or dynamic values, encode parameters to prevent HTTP 400 errors. For example, searching for "[email protected]" in an API requires encoding the @ symbol: /api/users/user%40example.com.
  • HTML Form Submissions (GET): When HTML forms use method="GET", browsers automatically URL-encode form data before submitting. If you're building URLs manually or using JavaScript to submit forms, you must encode data yourself. Form encoding uses application/x-www-form-urlencoded format, where spaces become + (though %20 also works).
  • International Characters and Unicode: Non-ASCII characters (accented letters like é, ñ, ü, Chinese/Japanese/Korean characters, Arabic, Cyrillic, emoji) must be URL-encoded. The character is first encoded to UTF-8 bytes, then each byte becomes %XX. For example, "café" becomes "caf%C3%A9" (é = UTF-8 bytes C3 A9).

Как работает кодирование URL?

Кодирование URL (процентное кодирование) преобразует символы, которые не разрешены в URL, в формат с использованием знака процента (%), за которым следуют две шестнадцатеричные цифры, представляющие байтовое значение символа. Вот технический процесс:

  • Шаг 1 - Идентификация небезопасных символов: Символы за пределами нерезервированного набора (A-Z, a-z, 0-9, -, _, ., ~) требуют кодирования. Зарезервированные символы (:, /, ?, #, @, и т.д.) должны быть закодированы при использовании в качестве данных, а не разделителей.
  • Шаг 2 - Преобразование в байты UTF-8: Символ сначала кодируется в последовательность байтов UTF-8. ASCII-символы производят один байт; не-ASCII символы производят 2-4 байта.
  • Шаг 3 - Преобразование каждого байта в %XX: Каждый байт представляется как знак процента (%) с последующими двумя заглавными шестнадцатеричными цифрами. Например, пробел (байт 0x20) становится %20.
  • Шаг 4 - Конкатенация результата: Закодированные байты заменяют исходный символ в строке URL. Многобайтовые символы производят несколько последовательностей %XX.

Пример: Строка "hello world" становится "hello%20world" (пробел = байт 0x20 = %20). Строка "café" становится "caf%C3%A9", потому что é — это байты UTF-8 C3 A9, каждый кодируется как %C3 и %A9.

RFC 3986 and URL Standard

Кодирование URL было стандартизировано в RFC 3986 (2005), который определяет синтаксис для универсальных идентификаторов ресурсов (URI). Стандарт указывает, какие символы безопасны (A-Z, a-z, 0-9, -, _, ., ~), а какие должны быть процентно-кодированы. До RFC 3986 различные системы использовали разные методы, что приводило к проблемам совместимости.

Security and URL Encoding

URL encoding makes data URL-safe but does not encrypt or secure it. Encoded URLs can be easily decoded. Always use HTTPS for sensitive data. Learn about encoding security

Кодирование URL в языках программирования

Каждый язык программирования предоставляет функции кодирования URL. Вот примеры:

// urlencode() - for form data (spaces become +)
$encoded = urlencode($data);

// rawurlencode() - RFC 3986 compliant (spaces become %20)
$encoded = rawurlencode($data);

// Building query strings
$params = http_build_query([
    'search' => 'coffee & tea',
    'category' => 'food/drink'
]);
// Result: search=coffee+%26+tea&category=food%2Fdrink
// encodeURIComponent() - for query parameters (use this!)
const encoded = encodeURIComponent('hello world & stuff');
// Result: hello%20world%20%26%20stuff

// encodeURI() - for complete URLs (rarely needed)
const fullUrl = encodeURI('https://example.com/path with spaces');

// Building URLs with parameters
const baseUrl = 'https://api.example.com/search';
const query = encodeURIComponent('[email protected]');
const url = `${baseUrl}?q=${query}`;
from urllib.parse import quote, quote_plus, urlencode

# quote() - RFC 3986 encoding
encoded = quote('hello world & stuff')
# Result: hello%20world%20%26%20stuff

# quote_plus() - form encoding (spaces become +)
encoded = quote_plus('hello world')
# Result: hello+world

# urlencode() - build query strings
params = urlencode({'search': 'coffee & tea', 'page': 1})
# Result: search=coffee+%26+tea&page=1
import (
    "net/url"
    "fmt"
)

// QueryEscape() - encode query parameter
encoded := url.QueryEscape("hello world & stuff")
// Result: hello+world+%26+stuff

// PathEscape() - encode path segments
encoded := url.PathEscape("hello/world")
// Result: hello%2Fworld

// Building URLs with parameters
u, _ := url.Parse("https://api.example.com/search")
q := u.Query()
q.Set("search", "coffee & tea")
u.RawQuery = q.Encode()
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;

// URL encoding (always specify UTF-8)
String encoded = URLEncoder.encode("hello world & stuff",
                                   StandardCharsets.UTF_8);
// Result: hello+world+%26+stuff

// Building URLs
String baseUrl = "https://api.example.com/search?q=";
String query = URLEncoder.encode("[email protected]",
                                 StandardCharsets.UTF_8);
String fullUrl = baseUrl + query;
require 'uri'
require 'cgi'

# URI.encode_www_form_component() - standard encoding
encoded = URI.encode_www_form_component('hello world & stuff')
# Result: hello+world+%26+stuff

# CGI.escape() - alternative
encoded = CGI.escape('hello world')

# Building query strings
params = URI.encode_www_form({search: 'coffee & tea', page: 1})
# Result: search=coffee+%26+tea&page=1
using System;
using System.Web;
using System.Net;

// HttpUtility.UrlEncode() - standard encoding
string encoded = HttpUtility.UrlEncode("hello world & stuff");
// Result: hello+world+%26+stuff

// Uri.EscapeDataString() - RFC 3986 (no System.Web dependency)
string encoded = Uri.EscapeDataString("hello world & stuff");
// Result: hello%20world%20%26%20stuff

Related Tools

Need to decode URL-encoded strings? Use our URL Decoder to convert percent-encoded text back to readable format.

Encoding binary data? Try our Base64 Encoder for converting binary data to text format.

Displaying text on web pages? Use our HTML Entity Encoder to safely encode HTML special characters.