본문 바로가기
개발&프로그래밍

[HTTP] URL 구조 파헤치기

by 재아군 2025. 2. 20.

URL 구조 파헤치기

 

URL의 기본 구조

scheme://username:password@host:port/path?query#fragment



1. 스키마(Scheme)

  • 프로토콜을 지정
  • 주요 스키마:
    • http: 일반 웹 통신
    • https: 보안 웹 통신
    • ftp: 파일 전송
    • mailto: 이메일
    • file: 로컬 파일



2. 사용자 정보(Userinfo)

  • username:password 형식
  • 거의 사용되지 않음 (보안상 권장되지 않음)
  • 예: ftp://user:pass@ftp.example.com/



3. 호스트(Host)

  • 도메인 이름 또는 IP 주소
  • 예시:



4. 포트(Port)

  • 서비스 포트 번호
  • 생략 시 기본값 사용:
    • HTTP: 80
    • HTTPS: 443
    • FTP: 21


5. 경로(Path)

  • 리소스 경로
  • 디렉토리/파일 구조 반영
  • 예: /products/category/electronics


6. 쿼리 스트링(Query String)

  • ? 뒤에 위치
  • key=value 형태
  • &로 여러 파라미터 구분
  • 예: ?page=1&limit=10&sort=desc


7. 프래그먼트(Fragment)

  • # 뒤에 위치
  • 페이지 내 특정 섹션 지정
  • 서버로 전송되지 않음
  • 예: #section-1


URL 작성 예시


기본 URL

https://www.example.com/products


포트 지정

https://localhost:3000/api/users


쿼리 파라미터 포함

https://api.example.com/search?q=keyword&page=1&limit=20

 

프래그먼트 포함

https://docs.example.com/guide#installation



URL 인코딩/디코딩

URL 인코딩이 필요한 경우

  • 특수문자 포함
  • 공백 포함
  • 비ASCII 문자 (한글 등)



JavaScript에서의 인코딩/디코딩

// 인코딩
const encoded = encodeURIComponent('안녕하세요?');
console.log(encoded); // '%EC%95%88%EB%85%95%ED%95%98%EC%84%B8%EC%9A%94%3F'

// 디코딩
const decoded = decodeURIComponent('%EC%95%88%EB%85%95%ED%95%98%EC%84%B8%EC%9A%94%3F');
console.log(decoded); // '안녕하세요?'



주요 인코딩 규칙

  • 공백: %20 또는 +
  • ?: %3F
  • =: %3D
  • &: %26
  • #: %23
  • /: %2F



쿼리 스트링 다루기


쿼리 스트링 파싱

// URLSearchParams 사용
const url = 'https://example.com/search?q=test&page=1';
const searchParams = new URLSearchParams(new URL(url).search);

console.log(searchParams.get('q')); // 'test'
console.log(searchParams.get('page')); // '1'


쿼리 스트링 생성

const params = new URLSearchParams();
params.append('q', 'search term');
params.append('page', '1');
params.append('category', 'books');

console.log(params.toString()); 
// 'q=search+term&page=1&category=books'


URL 조작하기


URL 객체 사용

const url = new URL('https://example.com/path');
url.searchParams.set('q', 'search');
url.hash = 'section-1';

console.log(url.toString());
// https://example.com/path?q=search#section-1


상대 URL 처리

const baseUrl = 'https://example.com/products/';
const relativeUrl = '../categories';
const absoluteUrl = new URL(relativeUrl, baseUrl);

console.log(absoluteUrl.href);
// https://example.com/categories


URL 검증과 정규식


URL 유효성 검사

function isValidUrl(string) {
    try {
        new URL(string);
        return true;
    } catch (err) {
        return false;
    }
}

console.log(isValidUrl('https://example.com')); // true
console.log(isValidUrl('not-a-url')); // false


URL 정규식 패턴

const urlPattern = /^(https?:\/\/)?([\da-z\.-]+)\.([a-z\.]{2,6})([\/\w \.-]*)*\/?$/;

console.log(urlPattern.test('https://example.com')); // true


보안 고려사항

  1. URL 파라미터 검증
  2. 중요 정보 노출 방지
  • 비밀번호, API 키 등을 URL에 포함하지 않기
  • 민감한 데이터는 POST 요청의 body로 전송
  1. URL 길이 제한 고려
  • 브라우저별 최대 URL 길이 제한 있음
  • 일반적으로 2000자 이내 권장

 

실무 팁

  1. URL 구성 시 고려사항
  • 의미있는 경로 사용
  • 대소문자 일관성 유지
  • 특수문자 사용 최소화
  1. RESTful URL 설계
  2. 검색엔진 최적화(SEO)
  • 사람이 읽기 쉬운 URL 사용
  • 의미있는 키워드 포함
  • 불필요한 파라미터 제거

 

 

댓글