홈으로 돌아가기

URL 인코딩(Percent Encoding)과 HTML 엔티티 인코딩의 작동 차이 분석

웹 환경에서 텍스트를 인코딩하는 방식은 다양하며, 적용 지점과 목적에 따라 기술 명세가 명확히 분리됩니다. 특히 혼동하기 쉬운 것이 **URL 인코딩 (퍼센트 인코딩)**과 **HTML 엔티티 인코딩**입니다. 두 인코딩 기법의 탄생 목적과 변환 대상, 그리고 크로스 사이트 스크립팅(XSS) 같은 웹 보안 측면에서의 역할 차이를 명확히 정리합니다.

1. URL 인코딩 (Percent Encoding)의 탄생 목적

URL 인코딩은 인터넷 주소창(URI/URL) 내부의 문자 전송 규격(RFC 3986)을 따르기 위한 기법입니다. URL에는 공백을 비롯해 ?, &, =, # 등 특별한 용도(파라미터 분할, 해시 마크 등)를 위한 **예약 문자(Reserved Characters)**들이 존재합니다.

  • 동작 방식: 예약 문자 또는 다국어(한글 등)가 원래 의도와 다른 주소 파라미터로 해석되는 오작동을 막기 위해, 해당 문자의 UTF-8 16진수 바이트 값 앞에 퍼센트 % 기호를 붙여 변환합니다.
  • 예시: 공백(Space) 문자는 %20으로, 한글 '가'는 %EB%B0%94로 치환되어 주소 창에 전달됩니다.

2. HTML 엔티티 인코딩 (HTML Entity Encoding)의 탄생 목적

HTML 엔티티 인코딩은 브라우저가 HTML 코드를 화면에 파싱하고 마크업하는 영역에서 안전하게 텍스트를 렌더링하기 위한 용도입니다. HTML 코드 안에는 태그를 구성하기 위한 <, >, &, ", ' 같은 문자들의 제어권이 매우 큽니다.

  • 동작 방식: 사용자가 게시판이나 입력 폼에 태그 형태를 직접 입력했을 때, 이것이 브라우저에 의해 실행되는 취약점(XSS)을 방지하기 위해 이들을 무해한 문자 표기 형식으로 변환합니다.
  • 예시: <&lt;로, >&gt;로, &&amp;로 치환되어 태그로서가 아닌 단순 텍스트로 안전하게 화면에 그려집니다.

3. 두 인코딩의 핵심 비교 요약

비교 항목 URL 인코딩 (Percent Encoding) HTML 엔티티 인코딩 (Entity Encoding)
주요 대상 인터넷 브라우저 주소창 및 HTTP 요청 헤더 HTML 문서의 바디 렌더링 텍스트 영역
인코딩 포맷 % + 16진수 바이트 (예: %20, %26) & + 엔티티 문자 또는 코드 (예: &amp;)
목적 네트워크 주소 오해석 방지 및 다국어 보존 브라우저 마크업 해석 차단 및 보안(XSS)
주요 JS API encodeURIComponent() 자체 함수 작성 필요 (DOM 치환 등)

4. JavaScript 기반 구현 가이드

**anyTools**는 클라이언트 사이드 변환 환경에서 이 두 포맷의 올바른 해석 차이를 직관적으로 검증할 수 있도록 설계되었습니다. 아래는 자바스크립트로 구현된 정밀 인코딩 및 디코딩 필터 예제입니다.

// HTML 엔티티 이스케이프 구현
function escapeHTML(str) {
    return str.replace(/[<>&"']/g, function(m) {
        switch (m) {
            case '<': return '&lt;';
            case '>': return '&gt;';
            case '&': return '&amp;';
            case '"': return '&quot;';
            case "'": return '&#x27;';
        }
    });
}

5. 올바른 적용 지점

주소 파라미터를 조립하거나 API 쿼리를 생성할 때는 **URL 인코딩**을, 유저가 입력한 문자열을 안전하게 DOM에 노출(innerHTML 사용 시 등)하고 보안을 유지하고 싶을 때는 **HTML 엔티티 인코딩**을 반드시 구분해서 적용해야 합니다. anyTools 인코더 도구를 통해 실제 변환 결과를 직접 검증하고 최적화해 보세요.

Encoding methods on the web differ by purpose and interface. Understanding the core difference between **URL Encoding (Percent Encoding)** and **HTML Entity Encoding** is key to managing network calls and preserving XSS web security. In this guide, we analyze both structures.

1. URL Encoding (Percent Encoding)

Defined by RFC 3986, URL encoding maps characters for the internet address bar. A URL utilizes **Reserved Characters** like ?, &, =, and # to separate parameters.

  • Mechanism: Converts non-ASCII characters or reserved symbols into a percent sign % followed by a two-digit hexadecimal representation of their UTF-8 bytes.
  • Example: A space is translated to %20, and the ampersand (&) becomes %26.

2. HTML Entity Encoding

HTML Entity encoding is used to safely render text inside the browser's Document Object Model (DOM). In HTML, characters like <, >, and & are reserved to build tag elements.

  • Mechanism: Replaces markup syntax symbols with predefined ASCII entities to prevent malicious scripts from executing (XSS attacks).
  • Example: The character < is encoded to &lt;, and & becomes &amp;.

3. Key Differences

Attribute URL Encoding HTML Entity Encoding
Scope URL Address Bar & Request Headers HTML Document Body Text Nodes
Format % + Hexadecimal (e.g. %20) & + Entity names (e.g. &lt;)
Main Goal Preserves parameter parsing structures Blocks markup execution & secures XSS
JS APIs encodeURIComponent() Custom regex-based escape handlers

4. JavaScript Code Reference

**anyTools** operates client-side logic to demonstrate how these formats parse text. Below is the secure JavaScript HTML escaping filter used in anyTools:

// Safe HTML Entity Escaping
function escapeHTML(str) {
    return str.replace(/[<>&"']/g, function(m) {
        switch (m) {
            case '<': return '&lt;';
            case '>': return '&gt;';
            case '&': return '&amp;';
            case '"': return '&quot;';
            case "'": return '&#x27;';
        }
    });
}

5. Conclusion

Use URL encoding when forming query strings, and HTML encoding when inserting unsanitized dynamic user strings into HTML templates. anyTools provides rapid encoders to test both processes on local sandboxed browsers.