LoginSignup
1
0

More than 5 years have passed since last update.

ローカルサーバに置いたHTMLファイルが画像を認識しない、CSSが読み込まれない

Posted at

表題の通りの問題が発生し、解決したのでまとめます。
この問題を解決してくれた未来電子テクノロジーの畑野さんにはこの場をお借りして改めて感謝申し上げます。

結論

cgi-binディレクトリ下のファイルはcgiファイルとして扱われるのでここに画像ファイルを置いても画像と認識してくれないし、cssファイルをcssとして認識してくれない。

前提の環境

概ねこの記事の通りの環境です。
pythonでサーバを立て、cgi-binディレクトリ下にpngファイルやcssファイルを置いていました。

ディレクトリ構造

解決前

Name/
 └web/
     └cgi-bin/
            ├index.py
            ├stylesheet.css
            └twitter.png

解決後

Name/
 └web/
     ├cgi-bin/
     │      └index.py
     ├stylesheet.css
     └twitter.png

サンプルコード

index.py
import sys
import io

sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding='utf-8')

print("Content-type: text/html; charset=utf-8")

print(
   """
    <!DOCTYPE html>
    <html lang="en" dir="ltr">
      <head>
        <meta charset="utf-8">
        <title>index</title>
        <link rel="stylesheet" href="stylesheet.css">
      </head>
      <body>
        <p class="change-color">色を変える</p>
        <p>↓画像を表示</p>
        <img src="twitter.png" alt="">
      </body>
    </html>
     """
)
stylesheet.css
.change-color{
  color:red;
}

解決前

index.py
<link rel="stylesheet" href="stylesheet.css">
<img src="twitter.png" alt="">

解決後

index.py
<link rel="stylesheet" href="../stylesheet.css">
<img src="../twitter.png" alt="">

パスを変えただけです。

実行結果

解決前

before.PNG

解決後

after.PNG

1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0